引用reference

A reference serves as an alternative name for an object. In real-world programs, references are primarily used as formal parameters to functions.

Each reference type "refers to" some other type. We cannot define a reference to a reference type, but can make a reference to any other data type.

A reference must be initialized using an object of the same type as the reference:

int ival = 1024;
int &refVal = ival; // ok: refVal refers to ival
int &refVal2;       // error: a reference must be initialized
int &refVal3 = 10;  // error: initializer must be an object

Because a reference is just another name for the object to which it is bound, all operations on a reference are actually operations on the underlying object to which the reference is bound.

When a reference is initialized, it remains bound to that object as long as the reference exists. There is no way to rebind a reference to a different object.

A consequence of this rule is that you must initialize a reference when you define it; initialization is the only way to say to which object a reference refers.

A const reference is a reference that may refer to a const object:

const int ival = 1024;
const int &refVal = ival; // ok: both reference and object are const
int &ref2 = ival;         // error: non const reference to a const object

We should know that const Reference is a Reference to const.

A const reference can be initialized to an object of a different type or to an rvalue, such as a literal constant:

int i = 42;
// legal for const references only
const int &r = 42;
const int &r2 = r + i;

The same initializations are not legal for nonconst references. 

This behavior is easiest to understand when we look at what happens when we bind a reference to an object of a different type. If we write

double dval = 3.14;
const int &ri = dval;

the compiler transforms this code into something like this:

int temp = dval; // create temporary int from the double
const int &ri = temp; // bind ri to that temporary

If ri were not const , then we could assign a new value to ri . Doing so would not change dval but would instead change temp . To the programmer expecting that assignments to ri would change dval , it would appear that the change did not work. Allowing only const references to be bound to values requiring temporaries avoids the problem entirely because a const reference is read-only.

A nonconst reference may be attached only to an object of the same type as the reference itself.

A const reference may be bound to an object of a different but related type or to an rvalue.

posted on 2014-04-22 17:53  江在路上2  阅读(74)  评论(0编辑  收藏  举报