intrusive_ptr in c++11

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 …

Read more

How can you efficiently check whether two std::weak_ptr pointers are pointing to the same object?

Completely rewriting this answer because I totally misunderstood. This is a tricky thing to get right! The usual implementation of std::weak_ptr and std::shared_ptr that is consistent with the standard is to have two heap objects: the managed object, and a control block. Each shared pointer that refers to the same object contains a pointer to …

Read more

Can you make a std::shared_ptr manage an array allocated with new T[]?

With C++17, shared_ptr can be used to manage a dynamically allocated array. The shared_ptr template argument in this case must be T[N] or T[]. So you may write shared_ptr<int[]> sp(new int[10]); From n4659, [util.smartptr.shared.const] template<class Y> explicit shared_ptr(Y* p); Requires: Y shall be a complete type. The expression delete[] p, when T is an array …

Read more

Why do shared_ptr deleters have to be CopyConstructible?

This question was perplexing enough that I emailed Peter Dimov (implementer of boost::shared_ptr and involved in standardization of std::shared_ptr) Here’s the gist of what he said (reprinted with his permission): My guess is that the Deleter had to be CopyConstructible really only as a relic of C++03 where move semantics didn’t exist. Your guess is …

Read more

How to release pointer from boost::shared_ptr?

Don’t. Boost’s FAQ entry: Q. Why doesn’t shared_ptr provide a release() function? A. shared_ptr cannot give away ownership unless it’s unique() because the other copy will still destroy the object. Consider: shared_ptr<int> a(new int); shared_ptr<int> b(a); // a.use_count() == b.use_count() == 2 int * p = a.release(); // Who owns p now? b will still …

Read more

is it better to use shared_ptr.reset or operator =?

There is indeed a substantial difference between: shared_ptr<T> sp(new T()); And: shared_ptr<T> sp = make_shared<T>(); The first version performs an allocation for the T object, then performs a separate allocation to create the reference counter. The second version performs one single allocation for both the object and the reference counter, placing them in a contiguous …

Read more