C++ Memory::make_shared



When a memory resource is generated for the first time, make_shared is utilized since it produces a shared_ptr more quickly. make_shared is exception-safe. The construction overhead is decreased by using the same function to allocate memory for the control block and the resource. If you don't use make_shared, you must explicitly build the object using a new expression before passing it to the shared_ptr function.

Syntax

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

shared_ptr<T> make_shared (Args&&... args);

Parameters

args − It is a list of zero or more types.

Example 1

Let's look into the following example, where we are using the make_shared and retriveing the value.

#include <iostream>
#include <memory>
void result(const std::shared_ptr<int>& i){
   (*i)++;
}
int main(){
   auto  value = std::make_shared<int>(8);
   result(value);
   std::cout << *value << std::endl;
}

Output

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

9

Example 2

Following is the another scenario, where we are going to use the make_shared and retrieving the value.

#include <iostream>
#include <memory>
int main (){
   std::shared_ptr<int> Result1 = std::make_shared<int> (14);
   auto Result2 = std::make_shared<int> (3);
   std::cout << "*Result1: " << *Result1 << '\n';
   std::cout << "*Result2: " << *Result2 << '\n';
   return 0;
}

Output

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

*Result1: 14
*Result2: 3

Example 3

Considering the following example where we are going make std::shared_ptr<std::function<void(int)>> from TP. then passing the TP as a argument to the make_shared.

#include <iostream>
#include <memory>
#include <functional>
struct TP {
   void operator()(int i){
      std::cout << i;
   }
};
int main(){
   auto fun = std::make_shared<std::function<void(int)>>(TP{});
   (*fun)(142);
   return 0;
}

Output

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

142
Advertisements