Content deleted Content added
→Pointers and references: Cleanup; int&const gives an error on g++ |
|||
Line 22:
===Pointers and references===
For pointer and reference types, the syntax is slightly more subtle. A pointer object can be declared as a <code>const</code> pointer or a pointer to a <code>const</code> object (or both). A <code>const</code> 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 <code>const</code> pointers.) A pointer to a <code>const</code> 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 <code>const</code> pointer to a <code>const</code> 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 )
int const i;
*ptr = 0; // Ok: modifies the pointee
ptr = &i; // Ok: modifies the pointer
*ptrToConst = 0; // Error! Cannot modify the pointee
ptrToConst = &i; // Ok: modifies the pointer
*constPtr = 0; // Ok: modifies the pointee
constPtr = &i; // Error! Cannot modify the pointer
*constPtrToConst = 0; // Error! Cannot modify the pointee
constPtrToConst = &i; // 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 before the star can be identified as the pointee type and everything to the left are the pointer properties. (For instance, in our example above, <code>constPtrToConst</code> can be read as a <code>const</code> pointer that refers to a <code>const int</code>.)
References follow similar rules. A declaration to a <code>const</code> reference is permitted for the sake of templates but is technically redundant since references can never be made to point to another object:
▲ int i = 42;
▲ int const & refToConst = i; // Ok
▲ int & const constRef = i; // Ok, but const is redundant here
Even more complicated declarations can result when using multidimensional arrays and references (or pointers) to pointers. Generally speaking, these should be avoided or replaced with higher level structures because they are confusing and prone to error.
|