简体   繁体   English

为什么“最重要的const”必须是const?

[英]Why does “most important const” have to be 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. http://herbsutter.com/2008/01/01/gotw-88-a-candidate-for-the-most-important-const/中,它提到“最重要的const”,其中C ++故意指定绑定临时对象在堆栈上引用const会延长临时生命周期到引用本身的生命周期。 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? 我想知道为什么c ++只允许在引用为const时延长对象的生命周期而不是在不引用时延长对象的生命周期? What is the rational behind the feature and why does it have to be const? 这个特征背后的理性是什么?为什么它必须是const?

Here's an example: 这是一个例子:

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

int main()
{
  float f = 3.0f;

  square(f);

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

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 ). 如果temporaries可以绑定到非const左值引用,上面会很乐意编译,但会产生相当令人惊讶的结果(输出为3而不是9 )。

Consider the following: 考虑以下:

int& x = 5;
x = 6;

What should happen if this was allowed? 如果允许这样做会怎么样? By contrast, if you did 相比之下,如果你这样做了

const int& x = 5;

there would be no legal way to modify x . 没有合法的方法来修改x

Note that const references can be bound to objects that don't even have an address normally. 请注意,const引用可以绑定到通常没有地址的对象。 A const int & function parameter can take an argument formed by the literal constant expression 42 . const int & function参数可以采用由文字常量表达式42形成的参数。 We cannot take the address of 42 , so we cannot pass it to a function that takes a const int * . 我们不能取42的地址,所以我们不能将它传递给一个带有const int *const int *

const references are specially "blessed" to be able to bind to rvalues such as this. const引用是特别“祝福”,能够绑定到这样的rvalues。

Of course, for traditional rvalues like 2 + 2 , lifetime isn't an issue. 当然,对于像2 + 2这样的传统价值,寿命不是问题。 It's an issue for rvalues of class type. 对于类类型的rvalues,这是一个问题。

If the binding of a reference is allowed to some object which, unlike 42 , does not have a pervasive lifetime, that lifetime has to be extended, so that the reference remains sane throughout its scope. 如果允许将引用绑定到某个对象,与42不同,该对象不具有普遍的生命周期, 必须延长该生命周期,以使引用在整个范围内保持理智。

It's not that the const causes a lifetime extension, it's that a non-const reference is not allowed. 这不是const导致生命周期扩展,而是不允许非const引用。 If that were allowed, it would also require a lifetime extension; 如果允许的话,还需要延长寿命; there is no point in allowing some reference which then goes bad in some parts of its scope. 允许一些参考在其范围的某些部分变坏然后没有意义。 That behavior undermines the concept that a reference is safer than a pointer. 这种行为破坏了引用比指针更安全的概念。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM