Aarkan Aarkan - 1 year ago 107
C++ Question

intrusive_ptr in c++11

Does C++11 have something equivalent to


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
because I have to manage the object through two (or more) smart pointers. I am unable to figure out a solution with something like

Answer Source

Does c++11 have something equivalent to boost::intrusive_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 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.

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.