C++ Memory Library - enable_shared_from_this



Description

It enables the shared_from_this member function in derived classes.

Declaration

Following is the declaration for std::enable_shared_from_this.

template <class T> class enable_shared_from_this;

C++11

template <class T> class enable_shared_from_this;

Parameters

T − It's a pointer class.

Return Value

none

Exceptions

noexcep − It doesn't throw any exceptions.

Example

In below example explains about std::enable_shared_from_this.

#include <iostream>
#include <memory>

struct C : std::enable_shared_from_this<C> { };

int main () {
   std::shared_ptr<C> foo, bar;

   foo = std::make_shared<C>();

   bar = foo->shared_from_this();

   if (!foo.owner_before(bar) && !bar.owner_before(foo))
      std::cout << "bother pointers shared ownership";

   return 0;
}

Let us compile and run the above program, this will produce the following result −

bother pointers shared ownership 
memory.htm
Advertisements