c++ - boost 侵入式指针

标签 c++ pointers boost shared-ptr boost-intrusive

我对 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 在与指针关联的控制 block 中管理引用计数本身。创建 shared_ptr 会增加引用计数。销毁 shared_ptr 会减少引用计数。当引用计数变为 0 时,指针被销毁。

intrusive_ptr 以完全相同的方式工作,但不管理引用计数本身。它只是向其客户端发出信号“现在必须增加引用计数”和“现在必须减少引用计数”。它通过调用提到的两个函数 intrusive_ptr_add_refintrusive_ptr_release 来实现。如果你不定义它们,你会得到一个编译错误。

将这些函数视为引用计数器的接口(interface)。使用 intrusive_ptr 表示引用计数在指针外部的某处进行管理(通常在指针本身中),并且指针只是侵入该引用计数,将其用于其目的。

关于c++ - boost 侵入式指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40137660/

相关文章:

c++ - &符号(&)符号如何在c++中工作?

c++ - Boost PTree 仅用于读取文件还是用于存储值?

c++ - 返回从成员映射的迭代器获得的 const 引用是否安全?

c++ - 后面加void违法吗?

c - 指针增量与C中的索引增量相比如何

c - 在 C 函数中修改数组

c++ - 如何在我的 C++ 代码中包含 boost 项目

string - 如何使用 Boost::asio 异步读取 std::string?

c++ - 获取指向映射 C++ 中结构的指针

c++ - 将二进制数的字符数组转换为C++中格雷码的计数器