Documentation Home >> Headers >> <jss/experimental_atomic.hpp> Header >> std::experimental::enable_shared_from_this class template

The enable_shared_from_this class template allows member functions of an object to retrieve a std::experimental::shared_ptr object that pointers to this and shares ownership with other std::experimental::shared_ptr objects that own this without needing direct access to one of those std::experimental::shared_ptr objects.

template<typename Derived>
class enable_shared_from_this{
    constexpr enable_shared_from_this() noexcept;
    enable_shared_from_this(enable_shared_from_this const&) noexcept;
    enable_shared_from_this& operator=(enable_shared_from_this const&);
    ~enable_shared_from_this() noexcept;
    shared_ptr<Derived> shared_from_this();
    shared_ptr<Derived const> shared_from_this() const;

To use enable_shared_from_this in a class X, publicly derive that class from enable_shared_from_this<X>:

class X: public std::experimental::enable_shared_from_this<X>{
    // whatever

For any X objects which are owned by std::experimental::shared_ptr instances constructed directly from a raw X pointer, or via std::experimental::make_shared<X>, the shared_from_this member function can be used to retrieve a std::experimental::shared_ptr instance that shares ownership with the other std::experimental::shared_ptr instances that own this.


class X: public std::experimental::enable_shared_from_this<X>{
    std::experimental::shared_ptr<X> foo();

std::experimental::shared_ptr<X> X::foo(){
    return shared_from_this();

std::experimental::shared_ptr<X> p(new X);
std::experimental::shared_ptr<X> p2=p->foo();

#include <experimental/atomic>

See Also