Why can const int& bind to an int?

后端 未结 8 744
野性不改
野性不改 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:05

    In C++, you can refer to non-const objects with references and/or pointers to const.

    int x = 10;
    const int& r = x; //OK
    const int* p = &x; //OK
    

    Of course, since x is not constant it can be changed. However, what you're basically saying by having a const reference to a non-const object is: I will not change this object via this reference/pointer. You still can change the object directly or through other references or pointers.

    Think of it as a read-only handle. Yes, the object itself may be mutable, but in many cases you may be willing to acquire and/or provide only a read-only access to that otherwise mutable variable.

提交回复
热议问题