我对 boost 的侵入式指针有点困惑。定义说:
"Every new
intrusive_ptr
instance increments the reference count by using an unqualified call to the functionintrusive_ptr_add_ref
, passing it the pointer as an argument. Similarly, when anintrusive_ptr
is destroyed, it callsintrusive_ptr_release
; this function is responsible for destroying the object when its reference count drops to zero. The user is expected to provide suitable definitions of these two functions. "
这是否意味着我必须实现这些方法,或者我可以做到?关键是,我们使用它是因为函数需要侵入式指针。我们在其他地方使用了共享指针,所以只是担心指针是否被管理,并且在没有更多引用时将被删除。
最佳答案
您必须提供这些功能。这就是 boost::intrusive_ptr
的运作方式。
让我们将它与 boost::shared_ptr
进行比较。 shared_ptr
在与指针关联的控制 block 中管理引用计数本身。创建 shared_ptr
会增加引用计数。销毁 shared_ptr
会减少引用计数。当引用计数变为 0 时,指针被销毁。
intrusive_ptr
以完全相同的方式工作,但不管理引用计数本身。它只是向其客户端发出信号“现在必须增加引用计数”和“现在必须减少引用计数”。它通过调用提到的两个函数 intrusive_ptr_add_ref
和 intrusive_ptr_release
来实现。如果你不定义它们,你会得到一个编译错误。
将这些函数视为引用计数器的接口(interface)。使用 intrusive_ptr
表示引用计数在指针外部的某处进行管理(通常在指针本身中),并且指针只是侵入该引用计数,将其用于其目的。
关于c++ - boost 侵入式指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40137660/