Does c++11 have something equivalent to boost::intrusive_ptr?
No.
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.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…