Skip to content

std::unique_ptr (C++11)

In a nutshell

A smart pointer that manages the lifecycle of dynamic objects via exclusive ownership semantics. It automatically destroys the object when it goes out of scope, and its size is identical to that of a raw pointer.

#include <memory>

Core API Cheat Sheet

OperationSignatureDescription
Create objecttemplate<class T> unique_ptr<T> make_unique(Args&&... args)(C++14) Create unique_ptr in an exception-safe manner
Constructorconstexpr unique_ptr(pointer p = pointer())Take ownership of a raw pointer
Destructor~unique_ptr()Destroy the managed object
Release ownershippointer release() noexceptRelinquish ownership and return the raw pointer
Reset pointervoid reset(pointer p = pointer())Destroy current object and take ownership of a new pointer
Get raw pointerpointer get() const noexceptReturn the managed raw pointer
Check if emptyexplicit operator bool() const noexceptDetermine if an object is held
DereferenceT& operator*() constAccess the managed object
Member accessT* operator->() constAccess members via pointer
Array subscriptT& operator[](size_t i) const(Array specialization) Access array elements

Minimal Example

cpp
// 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); // 转移所有权
    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 additional memory overhead.
  • Deterministic destruction: Releases memory immediately when the scope ends, aligning with embedded requirements for real-time performance and deterministic memory usage.
  • Perfectly supports the pImpl idiom, allowing implementation details to be hidden 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

v0.7.0-9-g940ec1b · 940ec1b · 2026-07-05