Why do some variables of the reference type bind rvalues, and some cannot?

#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 going on?
cout << c << endl;

return 0;
}

I do not understand why the compiler does not cause a compilation error. Since auto "force" c is a reference to an int constant, and links refer to lvalues, how does it work?

+4
source share
1 answer

It really doesn't work without const- you get a compilation error.

But there is const, i.e. You are not going to change the link c.

In this case, the standard has an additional wording in which the temporary value creferenced (result 1 + 2) will extend its life to the end of the life of the link.

auto. const .

+6

Source: https://habr.com/ru/post/1607435/


All Articles