#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;
}
Run Code Online (Sandbox Code Playgroud)
我不明白为什么编译器不会引发编译错误.由于auto"强制"c是对常量int的引用,并且引用被引用到左值,为什么它会起作用?
如果没有const- 这确实行不通- 你会得到一个编译错误.
但是就在const那里,即你不会修改c引用的内容.
对于这种情况,标准中还有一些措辞,即临时值c引用(结果1 + 2)将其生命周期延长到引用的生命周期结束.
这与此无关auto.这const就是在这里发挥作用.