Why can const int& bind to an int?

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

    An object cannot be modified "through" a const reference or a pointer to const of it. But a const reference or pointer to const doesn't impose any kind of run-time lock on the underlying object and (assuming it was not declared const) the original declaration or any non-const reference or pointer to non-const can still be used to modify it.

    Indeed if the object was not originally declared const then const-ness can be cast away and used to modify the underlying object.

    Indeed even if the object was originally declared const this may be possible (but is implementation dependent).

    const is a way of indicating that a function (or functions) shouldn't modify an object (either as an argument in our return value out or declaration).

    It doesn't (in general) mean the object can't be modified through that or some other reference/pointer.

    It also not possible to modify what a reference refers to. Or at least there is no valid way of doing it. In some circumstances it is possible in practice by jiggery pokery of obtaining an address of where a reference is held and modifying it like a pointer. That will usually fail in some circumstances because references are often optimized out of existence and because the compiler knows they 'cannot be modified' such violations might only be partially successful.

提交回复
热议问题