Pointers and References as member variables of const objects

后端 未结 2 1817
伪装坚强ぢ
伪装坚强ぢ 2021-01-13 09:01

The following code compiles fine. However I wonder if it is legal C++. So more specific, if I have a const object, am I allowed to modify variables through pointers/referenc

2条回答
  •  孤街浪徒
    2021-01-13 09:54

    I find the best way to think about const in C++ is that it protects the physical bits of the object. It has no real protection for objects that it refers to. You can control the object definition with const methods to provide deeper protection of values but by default C++ really only protects the physical object itself

    One of the reasons why C++ allows you to modify the contents of a pointer through a const value is that it really can't stop you. Imagine for a second that C++ disallowed that particular construct. You could trivially violate it by doing the following

    size_t t1 = (size_t)bar.a; // legal 
    int* t2 = (int*)t1;        // legal 
    *t2 = 3;                   // exactly the same as *bar.a = 3
    

提交回复
热议问题