How do I use make_unique and make_shared in C++?

In C++, make_unique and make_shared are factory functions provided by the standard library (available since C++14) to create smart pointers. They help in managing dynamic memory safely and efficiently. Below is an explanation and usage examples for both.

Using make_unique

make_unique is used to create an instance of a class wrapped in a std::unique_ptr. A std::unique_ptr is a smart pointer that owns a dynamically allocated object and ensures that there is only one owner at a time.

Usage of make_shared

make_shared is used to create an instance of a class wrapped in a std::shared_ptr. A std::shared_ptr allows multiple pointers to own the same object. It keeps track of how many shared pointers point to the same object, and the object is deleted when all shared pointers to it are destroyed.

Example Code


#include <iostream>
#include <memory>

class MyClass {
public:
    MyClass() { std::cout << "MyClass constructor called!" << std::endl; }
    ~MyClass() { std::cout << "MyClass destructor called!" << std::endl; }
};

int main() {
    // Using make_unique
    auto unique_ptr = std::make_unique<MyClass>();
    
    // Using make_shared
    auto shared_ptr = std::make_shared<MyClass>();

    return 0;
}
    

smart pointers make_unique make_shared unique_ptr shared_ptr C++ memory management