const_cast VS mutable ? any difference?

前端 未结 4 796
时光说笑
时光说笑 2021-02-06 03:50

From my understanding , mutable cancels the constness of a variable

Class A {
  void foo() const {
  m_a = 5;
}
mutable int m_a;
};
         


        
4条回答
  •  猫巷女王i
    2021-02-06 04:22

    The difference is that const_cast can't cheat, but mutable is an exception to the rules.

    On the first snippet m_a is mutable, and thus an exception to the rule that you can't modify data members on const member functions.

    On the second snippet, const_cast tries to cheat, but really can't: while the type has changed, actual modification is not allowed: the string is truly const. Attempting to modify it would cause the program to exhibit undefined behaviour.

提交回复
热议问题