Open In App

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.

Syntax

std::make_unique <object_type> (arguments);

Parameters

Return 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


Article Tags :