Why can reference members be modified by const member functions?

前端 未结 2 513
滥情空心
滥情空心 2021-01-17 14:59

The following will compile even though a const member function will modify the value of a member. How so ?

#include 

struct foo
{
    std::s         


        
2条回答
  •  北海茫月
    2021-01-17 15:54

    The const qualifier of a class member function indicates that this member function (e.g., foo::operator() const) cannot change the state of the object from the client's point of view (i.e., it's abstract state). This is not exactly the same as saying that the object's raw bits are not going to change.

    It is forbitten to C++ compilers to consider objects as raw bits, unless they can resolve the problem of aliasing. which in your case the compiler cannot. This is due to the fact that a non-constant alias exists (i.e., std::string &str) and consequently the state of the object is modifiable.

    That is, calling operator() on object a does not change the state of a (i.e., although ext has changed, the str still remains an alias of ext).

    The above also explains why pointing at an object with a pointer to constant (i.e., std::string * const str) does not guarantee that the object won't be modified. It only guarantees that the object won't change through that pointer.

提交回复
热议问题