Examples of std::make_unique
The following programs demonstrate how to implement std::make_unique() in our programs.
Example 1
C++
// 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++14
// 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.
std::make_unique in C++ 14
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.