Você está na página 1de 1

const-correctness - Wikipedia, the free encyclopedia

http://en.wikipedia.org/wiki/Const-correctness

Pointers and references


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 int int int { *ptr = 0; ptr = 0; * ptr, const * ptrToConst, * const constPtr, const * const constPtrToConst ) // OK: modifies the "pointee" data // OK: modifies the pointer

*ptrToConst = 0; // Error! Cannot modify the "pointee" data ptrToConst = 0; // OK: modifies the pointer *constPtr = 0; // OK: modifies the "pointee" data constPtr = 0; // Error! Cannot modify the pointer *constPtrToConst = 0; // Error! Cannot modify the "pointee" data constPtrToConst = 0; // Error! Cannot modify the pointer } To render the syntax for pointers more comprehensible, a rule of thumb is to read the declaration from right to left. Thus, everything to the left of the star can be identified as the pointee type and everything to the right of the star are the pointer properties. (For instance, in our example above, int const * can be read as a mutable pointer that refers to a non-mutable integer, and int * const can be read as a non-mutable pointer that refers to a mutable integer.) References follow similar rules. A declaration of a const reference is redundant since references can never be made to refer to another object: int i = 42; int const & refToConst = i; // OK int & const constRef = i; // Error the "const" is redundant Even more complicated declarations can result when using multidimensional arrays and references (or pointers) to pointers; however, some have argued that these are confusing and error-prone and that they therefore should generally be avoided or replaced with higher-level structures. C/C++ also allows the following syntax: const int* ptrToConst; //identical to: int const * ptrToConst, const int* const constPtrToConst;//identical to: int const * const constPtrToConst

2 of 8

24/05/12 16:20

Você também pode gostar