在http://herbsutter.com/2008/01/01/gotw-88-a-candidate-for-the-most-important-const/中,它提到"最重要的const",其中C++故意指定绑定临时对象在堆栈上引用const会延长临时生命周期到引用本身的生命周期.我想知道为什么c ++只允许在引用为const时延长对象的生命周期而不是在不引用时延长对象的生命周期?这个特征背后的理性是什么?为什么它必须是const?
Rei*_*ica 24
这是一个例子:
void square(int &x)
{
x = x * x;
}
int main()
{
float f = 3.0f;
square(f);
std::cout << f << '\n';
}
Run Code Online (Sandbox Code Playgroud)
如果temporaries可以绑定到非const左值引用,上面会很乐意编译,但会产生相当令人惊讶的结果(3而不是输出9).
Luc*_*ore 14
考虑以下:
int& x = 5;
x = 6;
Run Code Online (Sandbox Code Playgroud)
如果允许这样做会怎么样?相比之下,如果你这样做了
const int& x = 5;
Run Code Online (Sandbox Code Playgroud)
没有合法的修改方法x.