const int和int literal之间的区别

时间:2016-02-21 03:36:43

标签: c++11

我正在尝试了解auto,但有些问题让我很困惑。例如:

const int ci=0;
auto &g=ci;
auto &h=42;

为什么第二行是正确的而第三行是错误的?

1 个答案:

答案 0 :(得分:0)

您不能拥有指向r值的引用或指针。 r值是不会超出单个表达式的值。 r值只能出现在赋值的右侧。另一方面,l值仍可用于访问/使用,并且可以出现在作业的左侧或右侧。

42 = 1; //error. 42 is an r-value
someVariable = 1; //no problem, someVariable is an l-value
std::cout << &someVariable; // prints out the address of the variable as it's an l-value
std::cout << &42; // 42 was just created on the spot, and will disappear after this line. therefore, you can't have a pointer to it (or in short, it's an r-value) 

auto &h声明了一个引用,但由于42是一个r值,因此无法引用它,因为没有指向它的指针。 ci仍然是l值,尽管它被声明为const

相关问题