Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
295 views
in Technique[技术] by (71.8m points)

c++ - intrusive_ptr in c++11

Does C++11 have something equivalent to 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...