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

后端 未结 3 533
佛祖请我去吃肉
佛祖请我去吃肉 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 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).

提交回复
热议问题