我在 C++ 中有一个 const 函数,我从那里调用 C 函数。
class ClassEx
{
A* pPointer // declaration of the pointer
};
void
ClassEx::ClassFunction() const
{
int error = AFunctionInExternLib(&pPointer); //pPointer will be instantiated by this function.
}
//Signature of AFunctionInExternLib
Struct A
{
};
AFunctionInExternLib(A** pPointer);
现在,我有一个类型为 struct A 的 classEx 成员变量。 由于 Class::ClassFunction() 是一个 const 函数,我不能按原样传递 pPointer。所以我声明为
class ClassEx
{
mutable A* pPointer // declaration of the pointer
};
这编译得很好,但我想知道是否有任何其他方法可以在不使用可变关键字的情况下实现这一目标?
请注意我也试过了,
void
ClassEx::ClassFunction() const
{
A* pAnotherPointer = const_cast<A*>(pPointer);// remove constness
int error = AFunctionInExternLib(&pAnotherPointer);
}
但这会实例化 pAnotherPointer 而不是 pPointer。有没有办法把 pAnotherPointer 的地址分享给 pPointer?
这种做法有什么问题吗?
class ClassEx
{
A* pPointer // declaration of the pointer
};
void
ClassEx::ClassFunction() const
{
ClassEx* pTempPointer = const_cast<ClassEx*>(this);
int error = AFunctionInExternLib(&pTempPointer->pPointer);
}
最佳答案
有两种可能的情况:
pPointer
有助于ClassEx
对象的可观察(或逻辑)状态。在这种情况下,ClassFunction
会修改对象的可观察状态,因此不应const
。pPointer
是一个不影响可观察状态(例如内部缓存)的实现细节。在这种情况下,mutable
是正确的工具。另请注意,根据 C++11 线程安全规则,mutable
成员应该是线程安全的;也就是说,它们应该是原子的
或受互斥体保护。
关于c++ - C++ 中成员变量的关键字 mutable 的替代方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17102709/