Tuesday, January 13, 2009

c++: const pointer and pointer to const

For pointer and reference types, the syntax is slightly more subtle. A pointer object can be declared as a const pointer or a pointer to a const object (or both).

A const pointer cannot be reassigned to point to a different object from the one it is initially assigned, but it can be used to modify the object that it points to (called the "pointee"). (Reference variables are thus an alternate syntax for const pointers.)

A pointer to a const object, on the other hand, can be reassigned to point to another object of the same type or of a convertible type, but it cannot be used to modify any object.

A const pointer to a const object can also be declared and can neither be used to modify the pointee nor be reassigned to point to another object.

The following code illustrates these subtleties:

void Foo( int * ptr, int const * ptrToConst, int * const constPtr, int const * const constPtrToConst )
{ 
    *ptr = 0; // OK: modifies the pointee

    ptr = 0; // OK: modifies the pointer

    *ptrToConst = 0; // Error! Cannot modify the pointee

    ptrToConst = 0; // OK: modifies the pointer

    *constPtr = 0; // OK: modifies the pointee

    constPtr = 0; // Error! Cannot modify the pointer

    *constPtrToConst = 0; // Error! Cannot modify the pointee

    constPtrToConst = 0; // Error! Cannot modify the pointer 
}
source

No comments: