1

我在 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

};

这编译得很好,但我想知道是否有任何其他方法可以在不使用 mutable 关键字的情况下实现这一目标?

请注意我也试过这个,

 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); 
}
4

2 回答 2

2

There are two possible scenarios:

  1. pPointer contributes to the observable (or logical) state of the ClassEx object. In such case, ClassFunction modifies the observable state of the object and should therefore not be const.

  2. pPointer is an implementation detail which does no affect observable state (such as an internal cache). In such case, mutable is the correct tool to use. Also note that as per C++11 thread-safety rules, mutable members should be thread-safe; that is, they should be atomic or protected by a mutex.

于 2013-06-14T07:04:15.027 回答
0

Alternative to keyword mutable for member variables in C++

If there was an alternative to mutable, then we wouldn't need the keyword.

A* pAnotherPointer = const_cast<A*>(pPointer); - This is just removing the constness from a pointer, allowing you to call const methods on an object. The address is the same.

The best (as juanchopanza suggested) is to make ClassEx::ClassFunction() non-const.

于 2013-06-14T07:03:19.757 回答