Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C++

std::unique_ptr — exclusive resource ownership

std::unique_ptr is an exclusively owning smart pointer that automatically disposes of its resource. It cannot be copied, but ownership can be moved to another pointer.

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

Syntax

#include <memory>
std::unique_ptr<T> p = std::make_unique<T>(args...);
std::unique_ptr<T, Deleter> custom;
std::unique_ptr<T[]> array = std::make_unique<T[]>(count);

std::unique_ptr<T, D> from <memory> stores a pointer and a deleter. When the owner is destroyed, it invokes the deleter for a non-null pointer; this is an application of RAII. The default deleter uses delete for a single object. The parameter D allows customized resource disposal.

Use std::make_unique<T>(args...) to create an object. Copying a std::unique_ptr is forbidden. Initialization with auto q = std::move(p); transfers ownership to q and leaves p empty. std::move(p) alone does not transfer the resource: it enables selection of a move operation. Before dereferencing a potentially empty pointer, check it with if (p).

get() exposes the pointer without surrendering ownership. reset() disposes of the previous resource and leaves the owner empty; reset(ptr) accepts a replacement pointer. release() gives up the pointer without disposing of the resource, so the caller must arrange its eventual disposal. Do not create two independent owners of the same raw pointer or manually delete the result of get().

For arrays, use std::unique_ptr<T[]>: by default it calls delete[] and provides operator[] instead of operator* and operator->. std::make_unique<T[]>(count) creates such an array. This entry targets C++23; the supplied site publishes an evolving draft, not a frozen C++23 text. The repository compiler flag does not attest to the production runtime.

Examples

#include <iostream>
#include <memory>
#include <utility>

int main() {
    auto p = std::make_unique<int>(42);
    auto q = std::move(p);

    std::cout << std::boolalpha;
    std::cout << "p owns: " << static_cast<bool>(p) << '\n';
    std::cout << "value: " << *q << '\n';

    q.reset();
    std::cout << "q owns: " << static_cast<bool>(q) << '\n';
}

Result

p owns: false
value: 42
q owns: false

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