std::make_shared in C++
In C++, std::make_shared() is a function that returns a shared pointer to the object of specific type after dynamically creating it. It offers a safer and more efficient way to create shared pointers, reducing the chances of errors and improving performance. The function is declared in the <memory> header file.
In this use article, we will learn how to use std::make_shared() function in C++.
Syntax
std::make_shared<T> (args...)
Parameters
- T: Type of object which we want to create.
- args...: List of arguments for the constructor of object.
Return Value
- This function returns a shared pointer to the newly created object.
Example of std::make_shared()
// C++ Program to illustrate how std::make_shared
// function works
#include <iostream>
#include <memory>
using namespace std;
// Custom class for testing
class A {
public:
int data;
// Constructor to signal object creation
A(int val): data(val) {
cout << "Constructor called" << endl;
}
// Destructor to signal object deletion
~A() {
cout << "Destructor called" << endl;
}
};
int main() {
// Shared Pointer to the object of type A
shared_ptr<A> ptr = make_shared<A>(100);
cout << "Object data = "<< ptr->data << endl;
return 0;
}
Output
Constructor called Object data = 100 Destructor called
We can also use the following syntax:
auto ptr = make_shared<T> (args..)
leaving the type deduction to the compiler.
Need of std::make_shared()
Shared pointer to any object can already be created as:
std::shared_ptr<T> ptr (new T(args));
So why a dedicated function whose only purpose is to create shared pointer was needed?
Actually, when we create a shared pointer to already existing object, there will be 3 different memory allocation. One for control block of shared pointer, one for the object and one for the shared pointer itself. But with std::make_shared(), there are only two memory allocations. One for shared pointer and another for both control block and the object. It results in better efficiency than the conventional shared pointer.
Create Shared Pointer to Array (Since C++ 20)
Since C++ 20, std::make_shared() function can also be used create a dynamic array of any particular type and return a shared pointer to it.
Syntax
std::make_shared<T[]> (size)
or
std::make_shared<T[size]>()
where, size is the number of elements in the dynamic array.
Example of Creating Array using make_shared()
// C++ program to illustrate the creation
// of array using make_shared() function
#include <bits/stdc++.h>
using namespace std;
class A {
public:
A() {
cout << "Constructor Called" << endl;
}
~A() {
cout << "Destructor Called" << endl;
}
};
int main() {
// Creating an array of type A with 2 elements
auto sptr = make_shared<A[]>(2);
// Array will be automatically deallocated here
sptr = NULL;
return 0;
}
Output
Constructor Called
Constructor Called
Destructor Called
Destructor Called