C++11 中的 intrusive_ptr

intrusive_ptr in c++11(C++11 中的 intrusive_ptr)

本文介绍了C++11 中的 intrusive_ptr的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

C++11 是否具有与 boost::intrusive_ptr 等效的东西?

Does C++11 have something equivalent to boost::intrusive_ptr?

我的问题是我的 C++ 代码有一个 C 风格的界面.接口的两边都可以使用C++,但是出于兼容性的考虑,需要暴露C接口.我不能使用 std::shared_ptr 因为我必须通过两个(或更多)智能指针来管理对象.我无法找到类似 boost::intrusive_ptr 的解决方案.

My problem is that I have a C-style interface over my C++ code. Both sides of the interface can use C++, but exposing the C interface is required for compatibility reasons. I cannot use std::shared_ptr because I have to manage the object through two (or more) smart pointers. I am unable to figure out a solution with something like boost::intrusive_ptr.

推荐答案

c++11 是否有类似 boost::intrusive_ptr 的东西?

Does c++11 have something equivalent to boost::intrusive_ptr?

没有

它确实有 std::make_shared 这意味着 std::shared_ptr 几乎 (见下面的注释) 与侵入式智能指针,因为引用计数将存储在与对象本身相邻的内存中,从而提高引用和缓存使用的局部性.它还提供了 std::enable_shared_from_this,当您只有一个指向 shared_ptr 拥有的对象的内置指针时,它允许您检索 std::shared_ptr,但这不允许您使用不同的智能指针类型来管理对象.

It does have std::make_shared which means std::shared_ptr is almost (see note below) as efficient as an intrusive smart pointer, because the reference counts will be stored adjacent in memory to the object itself, improving locality of reference and cache usage. It also provides std::enable_shared_from_this which allows you to retrieve a std::shared_ptr when you only have a built-in pointer to an object owned by a shared_ptr, but that doesn't allow you to manage the object using different smart pointer types.

shared_ptr 期望完全负责管理对象.不同的智能指针类型可能只管理强"引用计数而不是弱"引用计数,这将导致计数不同步并破坏 shared_ptr 的不变量.

shared_ptr expects to be entirely responsible for managing the object. A different smart pointer type might only manage the "strong" refcount and not the "weak" refcount, which would allow the counts to get out of sync and break the invariants of shared_ptr.

注意:使用 make_shared 允许 shared_ptr 几乎 与侵入式指针一样有效.当使用 make_shared 时,对象和引用计数信息可以分配在单个内存块中,但仍然会有两个引用计数(对于强"和弱"计数)侵入式指针不是这种情况,因为它们不支持 weak_ptr.此外,shared_ptr 对象本身总是必须存储两个指针(一个由 shared_ptr::get() 返回,另一个指向控制块"的指针,包含引用计数并知道所拥有对象的动态类型)因此比侵入式指针占用空间更大.

Note: Using make_shared allows shared_ptr to be almost as efficient as an intrusive pointer. The object and the reference counting info can be allocated in a single chunk of memory when make_shared is used, but there will still be two reference counts (for the "strong" and "weak" counts) which isn't the case for intrusive pointers as they don't support a weak_ptr. Also, the shared_ptr object itself always has to store two pointers (the one that will be returned by shared_ptr::get() and another pointer to the "control block" that contains the reference counts and knows the dynamic type of the owned object) so has a larger footprint than an intrusive pointer.

这篇关于C++11 中的 intrusive_ptr的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:C++11 中的 intrusive_ptr

基础教程推荐