How is this C++ Reference Initialization Legal?

Viewed 87

I'm currently reading c++ Primer and in one of the exercises, it shows 2 types of reference initializations, one const and and one not, and in the one const, the reference points to 0.. I thought references could only point to objects!!

   int i = -1, &r = 0;         // illegal, r must refer to an object.

   const int i = -1, &r = 0;   // legal.

So the first one, int variable i is -1. Then int reference r refers to 0 which is invalid,gotcha

Now in the second one, const int i = -1, then const reference r = 0.. How?

I know references can't be const, the const is what the reference is referring to, and the book said that const references can refer to both const and non const objects(of the same type). This still doesn't explain why it can point to 0, which is not an object at all..

I'm not sure how the second statement is valid, someone please explain!

2 Answers

In

const int &r = 0;

a temporary object is created with the value 0, and then r is bound to that object. This is allowed because a const reference is allowed to bind to an rvalue. It also works with an rvalue reference:

int&& r = 0;  // ok

However, it won't work with int& because an int& variable can only bind to an lvalue.

Note that the temporary object that the reference binds to will live until the reference goes out of scope. See https://herbsutter.com/2008/01/01/gotw-88-a-candidate-for-the-most-important-const/

C++ specifically allows that an rvalue be bound to a const lvalue reference, so this is perfectly standard-conforming:

const int &r = 0;

Reference

  • An rvalue may be used to initialize a const lvalue reference, in which case the lifetime of the object identified by the rvalue is extended until the scope of the reference ends.
Related