C++ Memory::get_deleter



C++ Memory::get_deleter is helpful for libraries that create shared ptr instances for client code. When the client passes a shared ptr back, the library needs to know whether the shared ptr came from the client or the library, and if it did, it needs to access the private data that was stored in the deleter when the instance was created.

Syntax

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

D* get_deleter (const shared_ptr& sp) noexcept;

Parameters

sp − Its a shared pointer.

Example 1

Let's look into the following example, where we are going to use the get_deleter and getting the output.

#include 
#include 
int main(){
   std::shared_ptr iptr(new int(999), [](int*p) {
      delete(p);
   });
   auto _d = std::get_deleter(iptr);
   if(_d)
      std::cout<<"0";
   else
      std::cout<<"1";
   return 0;
}

Output

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

1

Example 2

Following is the another example, where we are going to use the get_deleter and retriveing the output.

#include 
#include 
struct D {
   void operator()(int* p){
      std::cout << "Welcome To Tutorialspoint\n";
      delete[] p;
   }
};
int main (){
   std::shared_ptr foo (new int[11],D());
   int * bar = new int[20];
   return 0;
}

Output

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

Welcome To Tutorialspoint

Example 3

let's look into the another scenario, where we are going to use the get_deleter and retriveing the output.

#include 
#include 
struct A {
   A(){
      std::cout << "HELLO\n";
   }
};
struct B {
   void operator()(A* p) const{
      std::cout << "WORLD\n";
      delete p;
   }
};
int main(){
   std::unique_ptr up(new A(), B());
   B& del = up.get_deleter();
}

Output

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

HELLO
WORLD
Advertisements