I have a back up copy of data that I would like to protect so I made it const
. I need to violate that const
ness on two occassions, once to store vi
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.
There is a little trick I learned looking at Qt's internals:
MyClass:circunventConst() const
{
MyClass* that = const_cast<MyClass*>(this);
that->myProtectedVariable = value;
}
Be aware that if you do this and the object really is const
, then modifying it after casting away the const
ness is undefined behaviour.
fgBlocks.CopyInto(const_cast<BlkArray&>(backUpCopy));
Same thing for the other one:
const_cast<BlkArray&>(backUpCopy).RemoveAll(true);