Skip to content

std::unique_ptr (C++11) ​

In a Nutshell ​

A smart pointer that manages the lifetime of dynamic objects through exclusive ownership semantics: it destroys the object automatically when it goes out of scope, and it is exactly the same size as a raw pointer.

#include <memory>

Core API Cheat Sheet ​

OperationSignatureDescription
Create objecttemplate<class T> unique_ptr<T> make_unique(Args&&... args)(C++14) Creates a unique_ptr in an exception-safe manner
Constructorconstexpr unique_ptr(pointer p = pointer())Takes over a raw pointer
Destructor~unique_ptr()Destroys the managed object
Release ownershippointer release() noexceptRelinquishes ownership and returns the raw pointer
Reset pointervoid reset(pointer p = pointer())Destroys the current object and takes over a new pointer
Get raw pointerpointer get() const noexceptReturns the managed raw pointer
Check if emptyexplicit operator bool() const noexceptTests whether it holds an object
DereferenceT& operator*() constAccesses the managed object
Member accessT* operator->() constAccesses members through the pointer
Array subscriptT& operator[](size_t i) const(Array specialization) Accesses array elements

Minimal Example ​

C++
// Standard: C++14
#include <iostream>
#include <memory>
struct Foo { ~Foo() { std::cout << "destroyed\n"; } };
int main() {
    std::unique_ptr<Foo> p = std::make_unique<Foo>();
    std::unique_ptr<Foo> q = std::move(p); // Transfers ownership
    std::cout << std::boolalpha << (p == nullptr) << "\n"; // true
} // "destroyed"

Embedded Applicability: High ​

  • Zero-overhead abstraction: compiles to the same size as a raw pointer, with no extra memory footprint
  • Deterministic destruction: releases immediately at end of scope, matching embedded demands for real-time behavior and deterministic memory usage
  • Fully supports the pImpl idiom, hiding implementation details and shortening compilation dependency chains
  • Introduces no control block, avoiding the thread-safety and memory-fragmentation overhead of shared_ptr

Compiler Support ​

GCCClangMSVC
4.42.92010

See Also ​


Part of the content is referenced from cppreference.com and licensed under CC-BY-SA 4.0

pdf-latest-4-g85128cc · 85128cc · 2026-10-05