我的代码无法编译。
int foobar()
{
// code
return 5;
}
int main()
{
int &p = foobar(); // error
// code
const int& x = foobar(); //compiles
}
为什么添加关键字const可以使代码通过编译?
最佳答案
在 C++ 中,临时对象不能绑定(bind)到非常量引用。
在
int &p = foobar();
右值表达式 foobar()
生成一个不能绑定(bind)到 p
的临时值,因为它是一个非常量引用。
const int &x = foobar();
将临时对象附加到 x
这是对 const 的引用可延长其生命周期。这是完全合法的。
关于c++ - 什么是必要的 const 关键字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5822401/