Why can const int& bind to an int?

后端 未结 8 550
野性不改
野性不改 2021-02-04 04:39

In the C++ primer, I found that const int & can bind with a int object.I don\'t understand that,because I think const int & should bind with a

8条回答
  •  我在风中等你
    2021-02-04 05:08

    Basically, const int & r promises not to mutate the value it's referencing. This is a stronger guarantee than int &. So, it's possible to refer to an int using a const int & reference. But you may not modify it. It's a subset of the operations possible on the value. However, it's not true the other way around, if you were trying to get a int & reference to an const int value, it would result in a compiler error because the value itself is immutable, and you are trying to get a mutable reference to this immutable value. The operations possible on the int & reference are a superset of what's possible on const int value.

提交回复
热议问题