为什么“最重要的常量”如此?必须是const? [英] Why does "most important const" have to be const?

查看:99
本文介绍了为什么“最重要的常量”如此?必须是const?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

http://herbsutter.com中/ 2008/01/01 / gotw-88-a-candidate-for-the-最重要的const / 提到最重要的const,其中C ++特意指定将临时对象绑定到对堆栈上的const可以将临时对象的生存期延长到引用本身的生存期。我想知道为什么c ++仅在引用为const而不是非引用时才允许延长对象的寿命?

In http://herbsutter.com/2008/01/01/gotw-88-a-candidate-for-the-most-important-const/ it mentions "most important const" where by C++ deliberately specifies that binding a temporary object to a reference to const on the stack lengthens the lifetime of the temporary to the lifetime of the reference itself. I was wondering why c++ only allows the lifetime of the object to be lengthened when the reference is const and not when it isn't? What is the rational behind the feature and why does it have to be const?

推荐答案

下面是一个示例:

void square(int &x)
{
  x = x * x;
}

int main()
{
  float f = 3.0f;

  square(f);

  std::cout << f << '\n';
}

如果临时对象可以绑定到非常量左值引用,则上面的代码会很高兴地编译,但产生令人惊讶的结果(输出 3 而不是 9 )。

If temporaries could bind to non-const lvalue references, the above would happily compile, but produce rather surprising results (an output of 3 instead of 9).

这篇关于为什么“最重要的常量”如此?必须是const?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆