How do you cast away const'ness when the function takes a reference to the object (and access non-const methods)?

前端 未结 3 656
伪装坚强ぢ
伪装坚强ぢ 2021-01-13 03:32

I have a back up copy of data that I would like to protect so I made it const. I need to violate that constness on two occassions, once to store vi

3条回答
  •  轮回少年
    2021-01-13 03:55

    There is a little trick I learned looking at Qt's internals:

    MyClass:circunventConst() const
    {
        MyClass* that = const_cast(this);
        that->myProtectedVariable = value;
    }
    

提交回复
热议问题