Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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 virgin data to it:

fgBlocks.CopyInto((BlkArray&)backUpCopy);

w.r.t.

result CopyInto(BlkArray &replica) const {/**/}

and again when I call RemoveAll() on it which is a non-const method:

((BlkArray)backUpCopy).RemoveAll(true);

Is the first cast (shown above, (BlkArray&)) correct? It's the one aspect of indirection I haven't cast to before now. Then again I'll add another unused aspect, that of casting away constness for calling an object's methods, which the compiler isn't accepting as shown above.

The members are declared like this:

BlkArray fgBlocks;
const BlkArray backUpCopy;

I'm trying to extend Correa's solution so have:

    BlkArray *pBUCopy = (BlkArray *)&backUpCopy;
    fgBlocks.CopyInto(*pBUCopy);

Only problem now is the compiler is failing due to

uninitialized member 'MyClass::backUpCopy' with 'const' type 'const BlockArray'

like image 836
John Avatar asked Feb 28 '12 00:02

John


1 Answers

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);
like image 110
Seth Carnegie Avatar answered Sep 28 '22 10:09

Seth Carnegie