Why does “most important const” have to be const?

后端 未结 3 532
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-16 10:44

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

相关标签:
3条回答
  • 2020-12-16 10:53

    Note that const references can be bound to objects that don't even have an address normally. A const int & function parameter can take an argument formed by the literal constant expression 42. We cannot take the address of 42, so we cannot pass it to a function that takes a const int *.

    const references are specially "blessed" to be able to bind to rvalues such as this.

    Of course, for traditional rvalues like 2 + 2, lifetime isn't an issue. It's an issue for rvalues of class type.

    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.

    It's not that the const causes a lifetime extension, it's that a non-const reference is not allowed. 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.

    0 讨论(0)
  • 2020-12-16 11:12

    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).

    0 讨论(0)
  • 2020-12-16 11:13

    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.

    0 讨论(0)
提交回复
热议问题