const_cast VS mutable ? any difference?

前端 未结 4 790
时光说笑
时光说笑 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:27

    Simply put, declaring a member variable as mutable makes it write-accessible from any constant method of that class without any other special syntax. const_cast on the other hand has to be performed whenever you want write access to an otherwise constant variable, and that variable doesn't even have to be a class member.

    Unless you want to explicitly allow write access to a member variable, using const_cast in every case of violation of const correctness is preferred, if only to clearly state your intentions.

    On a side note, const_cast can also be used to add or remove the volatile modifier.

提交回复
热议问题