增强侵入式指针
Boost intrusive pointer
我对 boost 的侵入式指针有点困惑。定义说:
"Every new intrusive_ptr
instance increments the reference count by
using an unqualified call to the function intrusive_ptr_add_ref
,
passing it the pointer as an argument. Similarly, when an
intrusive_ptr
is destroyed, it calls intrusive_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
在与指针关联的控制块中管理引用计数本身。创建 shared_ptr
会增加引用计数。销毁 shared_ptr
会减少引用计数。当引用计数变为 0 时,指针被销毁。
intrusive_ptr
以完全相同的方式工作,但不管理引用计数本身。它只是向其客户端 "now the refcount must be incremented" 和 "now the refcount must be decremented." 发出信号,它通过调用提到的两个函数 intrusive_ptr_add_ref
和 intrusive_ptr_release
来实现。如果你不定义它们,你会得到一个编译错误。
将这些函数视为引用计数器的接口。使用 intrusive_ptr
表示引用计数在指针外部的某处进行管理(通常在指针本身中),并且指针只是 侵入 在该引用计数上,将其用于其目的。
我对 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
在与指针关联的控制块中管理引用计数本身。创建 shared_ptr
会增加引用计数。销毁 shared_ptr
会减少引用计数。当引用计数变为 0 时,指针被销毁。
intrusive_ptr
以完全相同的方式工作,但不管理引用计数本身。它只是向其客户端 "now the refcount must be incremented" 和 "now the refcount must be decremented." 发出信号,它通过调用提到的两个函数 intrusive_ptr_add_ref
和 intrusive_ptr_release
来实现。如果你不定义它们,你会得到一个编译错误。
将这些函数视为引用计数器的接口。使用 intrusive_ptr
表示引用计数在指针外部的某处进行管理(通常在指针本身中),并且指针只是 侵入 在该引用计数上,将其用于其目的。