CodeBlanks Logo Icon CodeBlanks

make_unique and make_shared

Learn safe creation with make_unique and make_shared.

make_unique and make_shared

std::make_unique and std::make_shared are the safe way to create smart pointers. Instead of using new you use these: auto p = std::make_unique<int>(42); or auto p = std::make_shared<int>(42);.

These functions provide exception safety. Using make_unique instead of writing std::unique_ptr<int> p(new int(42)) prevents a memory leak if an exception occurs. Also make_shared allocates the object and the reference count in a single block; this is more efficient. Modern C++ avoids using new directly; the make_* functions are preferred.

Efficiency and safety

make_shared allocates the object and the control block (reference count) in a single memory block. This is more efficient than two separate new calls; it saves both memory and speed.

make_unique has the same cost as new but provides exception safety. Example: in a call f(std::unique_ptr<int>(new int(42)), g()) if g() throws, new int(42) leaks. Using f(std::make_unique<int>(42), g()) removes this risk. That is why make_* is always preferred.

Practice Use make_unique and make_shared

Create a unique_ptr with auto p1 = std::make_unique<int>(7); and a shared_ptr with auto p2 = std::make_shared<int>(14);. Print both values with std::cout separated by a space: *p1 and *p2.

Starter code

main.cpp
#include <iostream>
#include <memory>

int main() {
    // Create with make_unique and make_shared, print values
    return 0;
}

Sample solution

main.cpp
#include <iostream>
#include <memory>

int main() {
    auto p1 = std::make_unique<int>(7);
    auto p2 = std::make_shared<int>(14);
    std::cout << *p1 << " " << *p2;
    return 0;
}

Expected output

7 14

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Complete the make_unique call

Question
auto p = std::____<int>(42);
Answer
auto p = std::make_unique<int>(42);

Explanation: make_unique safely creates a unique_ptr.

2 What advantage does make_unique have over new?

main.cpp
// these two usages give the same result but
// make_unique is safer
  • Less memory usage
  • Faster execution
  • Exception safety Correct answer
  • Creates larger objects

Explanation: make_unique prevents memory leaks on exception.

3 Match each function to its purpose

Term Meaning
std::make_unique Exclusive safe
std::make_shared Shared safe
new int(42) Direct allocation
Single memory block make_shared benefit

All lessons in Intermediate