std::make_unique is a utility function in C++ that was introduced in C++14. It is used to create a unique_ptr object, which is a smart pointer that manages the lifetime of dynamically allocated objects. It is defined inside <memory> header file.
Syntax
std::make_unique <object_type> (arguments);
Parameters
- object_type: It is the type of object you want to create.
- arguments: It is the argument list for the constructor of object_type.
Return Type
- This function returns a unique_ptr of type object_type.
It is the preferred way to create a std::unique_ptr, as it is safer than using the new operator directly because the object is automatically destroyed when it goes out of scope.
Examples of std::make_unique
The following programs demonstrate how to implement std::make_unique() in our programs.
Example 1
// C++ code to implement std::make_unique()
#include <iostream>
#include <memory>
using namespace std;
class Geeks {
public:
Geeks() { cout << "Object Created\n"; } // constructor
~Geeks() { cout << "Object Destroyed"; } // destructor
};
void f()
{
// creating unique ptr object
unique_ptr<Geeks> o = make_unique<Geeks>();
}
int main()
{
f();
return 0;
}
Output
Object Created Object Destroyed
Example 2
// C++ code to implement std::make_unique()
#include <iostream>
#include <memory>
using namespace std;
class Geeks {
public:
int d;
// construtor
Geeks(int x)
{
this->d = x;
cout << "Object Created\n";
}
// destructor
~Geeks() { cout << "Object Destroyed"; }
};
void f()
{
// creating unique ptr object
unique_ptr<Geeks> o = make_unique<Geeks>(10);
cout << o->d << endl;
}
int main()
{
f();
return 0;
}
Output
Object Created 10 Object Destroyed
Advantages of std::make_unique
- Unlike new, make_unique is exception safe.
- No cleanup is necessary if make_unique is not evaluated.