|
|
|
|
&
instead of an asterisk, *
.
|
|
&
symbol.MikeyBoy wrote: |
---|
In answer to your first question, yes, that works fine, although the phrase is "pass by reference". |
TheIdeasMan wrote: |
---|
One advantage of a reference is that it always refers to something valid, whereas a ptr can be made to point at anything - valid or not. |
|
|
C++ references differ from pointers in several essential ways: 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. Note that for this reason, containers of references are not allowed. 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. For example: int& k; // compiler will complain: error: `k' declared as reference but not initialized
|
§ 8.3.2 5 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 (8.5.3) except when the declaration contains an explicit extern specifier (7.1.1), is a class member (9.2) declaration within a class definition, or is the declaration of a parameter or a return type (8.3.5); see 3.1. A reference shall be initialized to refer to a valid object or function. [ Note: in particular, a null reference cannot exist in a well-defined program, because the only way to create such a reference would be to bind it to the “object” obtained by dereferencing a null pointer, which causes undefined behavior. As described in 9.6, a reference cannot be bound directly to a bit-field. — end note ] |