4
#include <iostream>

using namespace std;
int main() {

//int& a = 3; <- Doesn't compile. Expression must be lvalue.
const auto& c = 1 + 2; // c is a constant reference to an int. (?)
                       // compiles fine. 1+2 is a rvalue? what's going on?
cout << c << endl;

return 0;
}

I don't understand why the compiler wont raise a compilation error. Since auto "forces" c to be a reference to a constant int, and references are refereed to lvalues, how come this works?

leemes
  • 44,967
  • 21
  • 135
  • 183
Alex Goft
  • 1,114
  • 1
  • 11
  • 23
  • 8
    The different is between `int&` and `const int&`, the type-deduction by `auto` plays no part in this. Constant references can bind to rvalues. – Some programmer dude Sep 15 '15 at 10:35
  • 5
    More on the "most important const" here: http://herbsutter.com/2008/01/01/gotw-88-a-candidate-for-the-most-important-const/ – Sneftel Sep 15 '15 at 10:36
  • 3
    possible duplicate of [Does a const reference prolong the life of a temporary?](http://stackoverflow.com/questions/2784262/does-a-const-reference-prolong-the-life-of-a-temporary) – NathanOliver Sep 15 '15 at 11:41

1 Answers1

6

This would indeed not work without the const -- you would get a compilation error.

But the const is there, i.e. you are not going to modify what c is referencing.

For this case, there is additional wording in the standard that the temporary value c is referencing (the result of 1 + 2) will have its lifetime extended to the end of the lifetime of the reference.

This is quite unrelated to auto. It's the const that is making the difference here.

DevSolar
  • 67,862
  • 21
  • 134
  • 209