Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C++

std::make_unique — creating an exclusively owned object

std::make_unique from <memory> creates an object or a dynamic array and returns a std::unique_ptr that manages it. Ownership is exclusive, and the memory is automatically released when the owner is destroyed.

Version: C++23; repository compiler flag, production runtime not attested

Syntax

#include <memory>
std::make_unique<T>(args...)
std::make_unique<T[]>(n)

std::make_unique from <memory> combines object creation with handing ownership to std::unique_ptr. The owner automatically deletes its managed object when destroyed, including when an exception causes scope exit. No manual delete is needed.

For a non-array type, std::make_unique<T>(args...) initializes an object of type T with the forwarded arguments and returns a std::unique_ptr<T>. The result can be moved but not copied: ownership is not shared.

For an array, std::make_unique<T[]>(n) returns std::unique_ptr<T[]>. Elements are value-initialized; for int, this means zeros. The element count is supplied at the call. A fixed-bound form such as std::make_unique<int[3]>() is prohibited by a deleted overload. Access through operator[] requires a valid index.

The example creates a number and three array elements, then changes the middle element. The expected output is 42 and 0 7 0 on separate lines. Both resources are released automatically at the end of the scope.

Examples

#include <iostream>
#include <memory>

int main() {
    auto value = std::make_unique<int>(42);
    auto numbers = std::make_unique<int[]>(3);
    numbers[1] = 7;

    std::cout << *value << '\n';
    std::cout << numbers[0] << ' ' << numbers[1] << ' '
              << numbers[2] << '\n';
}

Result

42
0 7 0

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources