Cpp pointers

The pointer can record an address in the main memory of the function.

The object name access the memory directly, as the name of the object is relate to some place of the memory, the pointer can store the address of the object. Then with the asterisk '*' you can access the memory with the type the pointer defined to be.

When you declare a pointer you must point it to an address, and the address must be used in the program.

You can make a space for the pointer with the keyword "new". And after the pointer have done with the memory it points, which you initialized with the keyword "new", you need to release the memory with the keyword "delete".

When using a pointer, two objects are involved: the pointer itself and the object pointed to. This means there are two possible layers of protection that we might want to impose with const:

    If we want to make sure that ptr cannot point to any other memory location, we can write it one of two ways:

    Type* const ptr = &vbl;
    Type* const ptr(&vbl);


    The pointer is a const but the addressed object can be changed.

    If we want to make sure that the value of vbl cannot be changed by dereferencing ptr, we can write it in two ways:

    const Type* ptr = &vbl;  
    const Type* ptr(&vbl);


    In this case, the addressed object is a constant but the pointer is not.

    In addition, if we want to impose both kinds of protection we can write:

    const Type* const ptr = &vbl;
    const Type* const ptr(&vbl);


    Here is a good way to remember which is which: Read each of the following definitions from right to left (starting with the defined variable).

    const char * x = &p; /* x is a pointer to const char*/
    char * const y = &q; /* y is a const pointer to char */  
    const char * const z = &r; /* z is a const pointer to a const char */

The keyword "const" is used to mark "char" or "*", like the char * if the const mark the char, like this const char * then the char is constant when accessed by the pointer, but the address where the pointer points can be changed.

When the '*' is marked with 'const', like this char * const y = & a, then the pointer can't be changed, the pointer can only point to one address.

If you want a totally constant pointer, then the pointer become to a constant, like const char * const y.

And if an address is valued to a const char pointer, then the address can't be assigned to a unconst char pointer.

原文地址:https://www.cnblogs.com/henyihanwobushi/p/2697531.html