const_cast VS mutable ? any difference?

前端 未结 4 797
时光说笑
时光说笑 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条回答
  •  春和景丽
    2021-02-06 04:31

    The difference is semantic - i. e. same generated code, same run-time results (constness is a purely compile-time construct anyway), but the two constructs convey a slightly different meaning.

    The idea is that you use mutable for variables that are in the class, but don't constitute the state of the object. The classic example is the current position in a blob object. Navigating in the blob does not count as "modifying" the blob in a way that matters. By using mutable, you're saying "this variable may change, but the object is still the same". You're stating that for this particular class, const-ness does not mean "all variables are frozen".

    const_cast, on the other way, means that you're violating existing const correctness and hope to get away with it. Probably because you're working with a 3rd party API that does not respect const (e. g. an old school C-based one).

提交回复
热议问题