On this page
  1. std::unique_ptr
  2. Overview
  3. Notes & Pitfalls
  4. Example

std::unique_ptr

Prev: memory | Up: memory | Next: std::make_unique
Rel: RAII & Destructors, Move Semantics, std::shared_ptr
Ref: cppreference — std::unique_ptr
Tags: #public #prog #cpp #stdlib #memory #tier/core


Overview

std::unique_ptr<T, Deleter> (<memory>) expresses exclusive ownership of a dynamically allocated object or OS handle. It is move-only (non-copyable), has the exact same size and performance as a raw pointer when using the default deleter, and automatically deletes its resource on scope exit.

Notes & Pitfalls

Example

#include <cassert>
#include <memory>
#include <utility>

int main() {
    auto p1 = std::make_unique<int>(99);
    auto p2 = std::move(p1);
    assert(p1 == nullptr && *p2 == 99);
}

Linked from

Related notes