How to enable_shared_from_this of both parent and derived

The OP solution can be made more convenient by defining the following on the base class. protected: template <typename Derived> std::shared_ptr<Derived> shared_from_base() { return std::static_pointer_cast<Derived>(shared_from_this()); } This can be made more convenient by placing it in a base class (for reuse). #include <memory> template <class Base> class enable_shared_from_base : public std::enable_shared_from_this<Base> { protected: template <class … Read more

Is auto_ptr deprecated?

UPDATE: This answer was written in 2010 and as anticipated std::auto_ptr has been deprecated. The advice is entirely valid. In C++0x std::auto_ptr will be deprecated in favor of std::unique_ptr. The choice of smart pointer will depend on your use case and your requirements, with std::unique_ptr with move semantics for single ownership that can be used … Read more

Where is shared_ptr?

There are at least three places where you may find shared_ptr: If your C++ implementation supports C++11 (or at least the C++11 shared_ptr), then std::shared_ptr will be defined in <memory>. If your C++ implementation supports the C++ TR1 library extensions, then std::tr1::shared_ptr will likely be in <memory> (Microsoft Visual C++) or <tr1/memory> (g++’s libstdc++). Boost … Read more

How is it possible (if it is) to implement shared_ptr without requiring polymorphic classes to have virtual destructor?

Yes, it is possible to implement shared_ptr that way. Boost does and the C++11 standard also requires this behaviour. As an added flexibility shared_ptr manages more than just a reference counter. A so-called deleter is usually put into the same memory block that also contains the reference counters. But the fun part is that the … Read more

std::auto_ptr to std::unique_ptr

You cannot do a global find/replace because you can copy an auto_ptr (with known consequences), but a unique_ptr can only be moved. Anything that looks like std::auto_ptr<int> p(new int); std::auto_ptr<int> p2 = p; will have to become at least like this std::unique_ptr<int> p(new int); std::unique_ptr<int> p2 = std::move(p); As for other differences, unique_ptr can handle … Read more