C++ Memory::enable_shared_from_this



For a shared_ptr managed object to acquire another shared_ptr of itself, we need a way to get hold of its control block. This is accomplished by using std::enable_shared_from_this function.

In essence, a handle with access to the control block, which may be either a shared_ptr or a weak_ptr, is the main source from which new shared_ptr instances can be created. An object can generate more shared_ptr for itself if it has that handle. A shared_ptr, on the other hand, acts as a powerful reference and affects the lifespan of the managed object.

Syntax

Following is the syntax for C++ Memory::enable_shared_from_this −

class enable_shared_from_this;

Parameters

T − It's a pointer class.

Example 1

Let's look into the following example, where we are using the enable_shared_from_this and the two shared_ptr's share the same object.

#include 
#include 
class Good : public std::enable_shared_from_this{
   public:
   std::shared_ptr getptr(){
      return shared_from_this();
   }
};
void check(){
   std::shared_ptr good0 = std::make_shared();
   std::shared_ptr good = good0->getptr();
   std::cout << "good.use_count() = " << good.use_count() << '\n';
}
int main(){
   check();
}

Output

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

good.use_count() = 2

Example 2

Consider the another scenario, where we are going to use enable_shared_from_this and each shared_ptr thinks they are the only owners of the objecct.

#include 
#include 
class Good : public std::enable_shared_from_this{
   public:
   std::shared_ptr getptr(){
      return shared_from_this();
   }
};
struct notgood {
   std::shared_ptr getptr(){
      return std::shared_ptr(this);
   }
   ~notgood(){
      std::cout << "Welcome\n";
   }
};
void Check(){
   std::shared_ptr bad0 = std::make_shared();
   std::shared_ptr bad = bad0->getptr();
   std::cout << "bad0.use_count() = " << bad.use_count() << '\n';
}
int main(){
   Check();
}

Output

On running the above code, it will display the output as shown below −

bad0.use_count() = 1
Welcome
double free or corruption (out)
Aborted (core dumped)

Example 3

In the following example we are going to make shared_from_this is called without having std::shared_ptr owing the caller.

#include 
#include 

class Good : public std::enable_shared_from_this{
   public:
   std::shared_ptr getptr(){
      return shared_from_this();
   }
};
void check(){
   try {
      Good not_so_good;
      std::shared_ptr gp1 = not_so_good.getptr();
   } catch(std::bad_weak_ptr& e) {
      std::cout << e.what() << '\n';
   }
}
int main(){
   check();
}

Output

when the code gets executed, it will generate the output as shown below −

bad_weak_ptr
Advertisements