0
0
CppConceptBeginner · 3 min read

What is make_unique in C++: Simple Explanation and Usage

make_unique is a C++ function template that creates a smart pointer called std::unique_ptr to manage dynamic memory safely. It simplifies memory allocation by automatically creating an object and returning a unique pointer that owns it, preventing memory leaks.
⚙️

How It Works

Imagine you want to buy a book and keep it safe so no one else can accidentally lose or damage it. make_unique works like a special box that holds your book (the object) and makes sure only you have the key to open it. This box automatically takes care of cleaning up the book when you no longer need it.

In C++, make_unique creates an object on the heap (dynamic memory) and returns a std::unique_ptr that owns this object. This pointer ensures that the object is deleted automatically when the pointer goes out of scope, so you don't have to manually call delete. It also prevents multiple pointers from owning the same object, avoiding confusion and errors.

💻

Example

This example shows how to use make_unique to create and use a unique pointer managing an integer.

cpp
#include <iostream>
#include <memory>

int main() {
    // Create a unique_ptr to an int with value 42
    std::unique_ptr<int> ptr = std::make_unique<int>(42);

    // Use the pointer to access the value
    std::cout << "Value inside unique_ptr: " << *ptr << std::endl;

    // No need to delete ptr manually; it cleans up automatically
    return 0;
}
Output
Value inside unique_ptr: 42
🎯

When to Use

Use make_unique whenever you want to create an object on the heap and ensure it is automatically cleaned up without manual delete. It is perfect for managing resources safely and avoiding memory leaks.

Common real-world uses include managing objects in classes, returning dynamically created objects from functions, or handling resources that need exclusive ownership, like file handles or network connections.

Key Points

  • make_unique creates a std::unique_ptr managing a new object.
  • It prevents manual memory management and reduces errors.
  • Only one unique_ptr can own the object at a time.
  • Introduced in C++14 as a safer alternative to new and manual delete.

Key Takeaways

make_unique safely creates and owns dynamic objects with automatic cleanup.
It prevents memory leaks by managing object lifetime automatically.
Use it instead of raw pointers for exclusive ownership of resources.
Introduced in C++14, it is the recommended way to create unique_ptr.
It simplifies code and improves safety by avoiding manual new and delete.