什么是const关键字是必要的

use*_*212 4 c++ const reference

我的代码没有编译.

int foobar()
{
    // code
    return 5;
}

int main()
{
   int &p = foobar(); // error
   // code

   const int& x = foobar(); //compiles
}
Run Code Online (Sandbox Code Playgroud)

为什么添加关键字const会使代码编译?

Pra*_*rav 9

在C++中,临时数不能绑定到非常量引用.

 int &p = foobar(); 
Run Code Online (Sandbox Code Playgroud)

rvalue表达式foobar()生成一个无法绑定的临时表,p因为它是一个非const引用.

 const int &x = foobar();
Run Code Online (Sandbox Code Playgroud)

附加x对const的引用的临时值会延长其生命周期.这完全合法.