- android - 多次调用 OnPrimaryClipChangedListener
- android - 无法更新 RecyclerView 中的 TextView 字段
- android.database.CursorIndexOutOfBoundsException : Index 0 requested, 光标大小为 0
- android - 使用 AppCompat 时,我们是否需要明确指定其 UI 组件(Spinner、EditText)颜色
我读过 article about using boost::intrusive_ptr for managing COM objects .作者展示了一个包装类,它负责为通常的 COM 语义调整智能指针。这是类:
template <typename T>
class WrapPtr
{
public:
WrapPtr(boost::intrusive_ptr<T>& ref)
: m_ref(ref), m_ptr(0)
{
}
~WrapPtr()
{
// The second parameter indicates that the reference count should not be incremented
m_ref = boost::intrusive_ptr(m_ptr, false);
}
operator T**()
{
return &m_ptr;
}
operator void**()
{
// Some COM functions ask for a pointer to void pointer, such as QueryInterface
return reinterpret_cast<void**>(&m_ptr);
}
private:
T* m_ptr;
boost::intrusive_ptr<T> m_ref;
};
template <typename T>
WrapPtr<T> AttachPtr(boost::intrusive_ptr<T>& ref)
{
return WrapPtr<T>(ref);
}
我不明白的是析构函数。它会丢弃当前的 m_ref 对象(这当然会导致对 Release
的调用),但随后他会分配一个从 m_ptr 成员构造的新的 intrusive_ptr。我不明白为什么在析构函数中需要这样做,因为 Wrapper 类持有 intrusive_ptr 的拷贝,而不是对它的引用。如果被调用者改变了指向的对象,这个改变将在析构函数离开后丢失。这是这里的错误还是我遗漏了什么?
最佳答案
在我曾经看到的一个类似的“安全地址”类中,该类有一个 intrusive_ptr 引用(intrusive_ptr<T>&
),而不是实际对象(intrusive_ptr<T>
)。您发布的类(class)实际上不会影响客户的 intrusive_ptr。所以看起来代码只是有问题:它应该持有对客户端 intrusive_ptr 的引用,而不是一个单独的 intrusive_ptr 对象:
template <typename T>
class WrapPtr
{
private:
T* m_ptr;
boost::intrusive_ptr<T>& m_ref;
...
};
编辑:我忘了回答你的实际问题:)
通过上述修复,析构函数的作用变得更加清晰:它将客户端的 intrusive_ptr 设置为保存通过调用 operator T** 设置的指针或 operator void** 并将其传递给“getter”方法(例如 QueryInterface)。
关于c++ - 为什么作者要在包装类的析构函数中创建这个 boost::intrusive_ptr 的新实例?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14424764/
我是一名优秀的程序员,十分优秀!