c++ - C++ 中成员变量的关键字 mutable 的替代方法

标签 c++ constants mutable

我在 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); 
}

最佳答案

有两种可能的情况:

  1. pPointer 有助于ClassEx 对象的可观察(或逻辑)状态。在这种情况下,ClassFunction 会修改对象的可观察状态,因此不应 const

  2. pPointer 是一个不影响可观察状态(例如内部缓存)的实现细节。在这种情况下,mutable 是正确的工具。另请注意,根据 C++11 线程安全规则,mutable 成员应该是线程安全的;也就是说,它们应该是原子的或受互斥体保护。

关于c++ - C++ 中成员变量的关键字 mutable 的替代方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17102709/

相关文章:

c++ - 索引到 CHOLMOD 密集 vector 数组

c++ - 为什么函数不获取动态数组? (我正在使用指针和引用)

c++ - 如何从传感器(RFID)获取原始数据?

c++ - 指向常量 int 的常量指针

python - 列表列表更改意外地反射(reflect)在子列表中

c++ - 如何从 256 位消息中获取特定位?

c++ - 错误推回对 const vector 元素的引用

c++ - 临时对象最初是 const 吗?

Python 对象初始化错误。还是我误解了对象的工作原理?

Java:函数式编程中线程之间的状态共享