为什么键入&不能绑定const左值

时间:2017-06-26 17:43:40

标签: c++ visual-c++ c++-cli

为什么输入&不能绑定到const L值?我理解类型&可以绑定到L值但是const L值只是某种类型变量的不可变地址?我的第二个问题是为什么键入&不能绑定一个" mordifiable R-value"要么?非常感谢您的帮助。

1 个答案:

答案 0 :(得分:2)

  

为什么选择&不能绑定到const L值?

如果允许,您将能够修改const对象。

void foo(int& v)
{
   v = 10;
}

int main()
{
   const int i = 20;
   int& ref = i;
   foo(ref);  // If the previous line were allowed, the value of i will be 10 after
              // the function returns, which violates the const-ness of i
}