简体   繁体   中英

References and constants

We can bind a reference to an object only, not to a literal or to the result of a more genreal expression.

int i=42;
double d=1.2;
int &r=10;//error:initializer must be an object.
int &r1=d; //error: initializer must be an int object

While we can bind a reference to a constant to an object, a literal and to the result of a more general expression as shown-

int j=45;
double d=1.2;
const int &r2=j; // works
const int &r2=60; //works
const int &r3=d; //works

The reason mentioned in Primer is that the compiler creates a temporary object of type 'constant int' here.

const int temp=d;
const int &r3=temp;

But if this is the case, then this logic must apply to both the above cases, and both should work if the types of reference and the object are different. But in actual, if the types are different, then the program works only when the reference is of type 'reference to a constant' otherwise it shows an error. why ?

Simply put: a const reference prolongs the lifetime of a temporary. It's a feature of the language to avoid dangling references that might arise from the temporary destroyed.

More precisely the C++ standard says:

[class.temporary]/p5

There are three contexts in which temporaries are destroyed at a different point than the end of the fullexpression [...] The third context is when a reference is bound to a temporary.

and [dcl.init.ref]/p5.2

A reference to type “cv1 T1” is initialized by an expression of type “cv2 T2” as follows:

[..lvalue and conversion cases..]

Otherwise, the reference shall be an lvalue reference to a non-volatile const type (ie, cv1 shall be const), or the reference shall be an rvalue reference

As for what rvalue/lvalue are, I recommend reading about value categories .

Finally a word of advice if you're using MSVC: turn your warnings on for this particular issue.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM