- It is not possible to refer directly to a reference object after it is defined; any occurrence of its name refers directly to the object it references.
- Once a reference is created, it cannot be later made to reference another object; it cannot be reseated. This is often done with pointers.
- References cannot be null, whereas pointers can; every reference refers to some object, although it may or may not be valid.
- References cannot be uninitialized. Because it is impossible to reinitialize a reference, they must be initialized as soon as they are created. In particular, local and global variables must be initialized where they are defined, and references which are data members of class instances must be initialized in the initializer list of the class's constructor.
- Most compilers will support a null reference without much complaint, crashing only if you try to use the reference in some way.
- References become invalid if they refer to an object with automatic allocation which goes out of scope.
- References become invalid if they refer to an object inside a block of dynamic memory which has been freed.
- Undefined behavior and invalid reference (initialized by dereferencing a null pointer):
int *ip = 0; int &ir = *ip;
- References exhibit polymorphic capabilities, which is similar to pointers.
- References not qualified with const can only be bound to addressable values, not rvalues.
- References not qualified with const cannot be bound to temporary objects.
- Never return references to local or temporary objects.
- It is unspecified whether or not a reference requires storage.
- There shall be no references to references, no arrays of references, and no pointers to references.
- The declaration of a reference shall contain an initializer except when the declaration contains an explicit extern specifier, is a class member declaration within a class declaration, or is the declaration of a parameter or a return type.
- A reference cannot be bound directly to a bitfield.
- Given typedef int & iRef;, the declaration const iRef ir=5; is incorrect. Here, the qualifier const will be ignored. However, the following code is correct.
typedef const int & ciRef; ciRef ir = 5;
- For pointers, there may be both const pointers and pointers to const variables; for references, there is no const references, at least not directly. By nature, reference is const and cannot be reassigned. In this sense, the term "const reference" always refers to "reference to const variable".
References:
Wikipedia: Reference
Rvalue References and Move Semantics
No comments:
Post a Comment