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

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

How is the std::tr1::shared_ptr implemented?

shared_ptr must manage a reference counter and the carrying of a deleter functor that is deduced by the type of the object given at initialization. The shared_ptr class typically hosts two members: a T* (that is returned by operator-> and dereferenced in operator*) and a aux* where aux is a inner abstract class that contains: … Read more

Equality-compare std::weak_ptr

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

Why isn’t there a std::shared_ptr specialisation?

The LWG (Library Working Group of the C++ committee) briefly considered the possibility but the idea wasn’t without controversy. Though the controversy was mainly about a feature added to the shared_ptr<T[]> proposal that could have been jettisoned (arithmetic on shared_ptr<T[]>). But ultimately the real real reason is that though it was discussed, there was never … Read more