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

前端 未结 3 635
伪装坚强ぢ
伪装坚强ぢ 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:53

    You can circumvent this problem by simply marking all methods as const, except RemoveAll and CopyFrom, the latter being made to be a method of BlkArray that either implements the logic or passes *this to CopyInto.

    To be more secure about who can clear the data / copy new stuff into it, you may make those methods private and declare the necessary classes as friends, or use the passkey pattern to protect those two methods.

    0 讨论(0)
  • 2021-01-13 03:55

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

    MyClass:circunventConst() const
    {
        MyClass* that = const_cast<MyClass*>(this);
        that->myProtectedVariable = value;
    }
    
    0 讨论(0)
  • 2021-01-13 04:08

    Be aware that if you do this and the object really is const, then modifying it after casting away the constness is undefined behaviour.

    fgBlocks.CopyInto(const_cast<BlkArray&>(backUpCopy));
    

    Same thing for the other one:

    const_cast<BlkArray&>(backUpCopy).RemoveAll(true);
    
    0 讨论(0)
提交回复
热议问题