当函数引用对象(并访问非const方法)时,如何丢弃const'ness? [英] How do you cast away const'ness when the function takes a reference to the object (and access non-const methods)?
问题描述
我有一个备份的数据副本,我想保护,所以我使它 const
。我需要在两次出现时违反 const
ness,一次将原始数据存储到它:
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 virgin data to it:
fgBlocks.CopyInto((BlkArray&)backUpCopy);
wrt
result CopyInto(BlkArray &replica) const {/**/}
当我调用 RemoveAll()
时,它是一个非const方法:
and again when I call RemoveAll()
on it which is a non-const method:
((BlkArray)backUpCopy).RemoveAll(true);
是第一个转换(如上所示,(BlkArray&)
)是否正确?这是间接的一个方面,我现在还没有施放。然后再次添加另一个未使用的方面,抛出 const
ness调用一个对象的方法,编译器不接受如上所示。
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 const
ness for calling an object's methods, which the compiler isn't accepting as shown above.
成员声明如下:
BlkArray fgBlocks;
const BlkArray backUpCopy;
我试图扩展Correa的解决方案,所以有:
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
未初始化的成员'MyClass :: backUpCopy'with'const'type'const BlockArray'
uninitialized member 'MyClass::backUpCopy' with 'const' type 'const BlockArray'
推荐答案
注意,如果你这样做,对象真的是 const
,然后修改它, > const ness是未定义的行为。
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));
同一件事:
const_cast<BlkArray&>(backUpCopy).RemoveAll(true);
这篇关于当函数引用对象(并访问非const方法)时,如何丢弃const'ness?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!