DefiningMultiple References
We can define multiple references in a single type definition. Each identifier that is a reference must be preceded by the & symbol:
- int i = 1024, i2 = 2048;
- int &r = i, r2 = i2;
int i3 = 1024, &ri = i3; int &r3 = i3, &r4 = i2;
const References
A const reference is a reference that may refer to a const object:
- const int ival = 1024;
- const int &refVal = ival;
- int &ref2 = ival;
const reference 不能写入,但并不代表其值一定不会改变,因为它引用的对象有可能是non-const,会被其他代码修改。
We can read from but not write to refVal. Thus, any assignment to refVal is illegal. This restriction should make sense: We cannot assign directly to ival and so it should not be possible to use refVal to change ival.
For the same reason, the initialization of ref2 by ival is an error: ref2 is a plain, nonconst reference and so could be used to change the value of the object to which ref2 refers. Assigning to ival through ref2 would result in changing the value of a const object. To prevent such changes, it is illegal to bind a plain reference to a const object.
注意:const reference 和reference to const 是一回事,提法不同而已。因为C++(www.cppentry.com)里没有真正的non-constreference( 指可以rebind的reference,见前页),所以non-const reference 就借指reference to non-const了。这和指针不同,const pointer 和pointer to const 是两码事,C++(www.cppentry.com) 里甚至还有const pointer to const。
TERMINOLOGY: CONST REFERENCE IS A REFERENCE TO CONST
C++(www.cppentry.com) programmers tend to be cavalier in their use of the term const reference. Strictly speaking, what is meant by “const reference” is “reference to const.” Similarly, programmers use the term “nonconst reference” when speaking of reference to a nonconst type. This usage is so common that we will follow it in this book as well.
A const reference can be initialized to an object of a different type or to an rvalue (Section 2.3.1, p. 45), such as a literal constant:
- int i = 42;
-
- const int &r = 42;
- const int &r2 = r + i;
The same initializations are not legal for nonconst references. Rather, they result in compile-time errors. The reason is subtle and warrants an explanation.
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;
- const int &ri = temp;
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 referencemay be bound to an object of a different but related type or to an rvalue.