c++ - 什么是必要的 const 关键字

标签 c++ reference constants

我的代码无法编译。

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/

相关文章:

c++ - 显式链接的 DLL 中的 CDecl 清理代码

reference - iOS7创建和使用SKTextureAtlas的正确方法是什么?

visual-studio - Visual Studio 递归复制本地

c++ - 如果成员函数影响逻辑状态而不是按位状态,它们应该是 "const"吗?

C++ 创建一个 std::vector<float> const 对象

c++ - boost asio 在线程中运行 io_service

c++ - vector iterator not incrementable,这与iterator和erase的操作有关

c++ - 返回私有(private) vector

java - 当另一个线程正在使用映射时,重新分配对映射的引用会引发异常吗?

delphi - 在Delphi 7中,为什么我可以给const赋值?