Skip to content

std::unique_ptr (C++11)

In a Nutshell

A smart pointer that manages the lifetime of a dynamic object through 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 Quick Reference

OperationSignatureDescription
Create objecttemplate<class T> unique_ptr<T> make_unique(Args&&... args)(C++14) Exception-safe creation of unique_ptr
Constructorconstexpr unique_ptr(pointer p = pointer())Takes ownership of 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 ownership of a new pointer
Get raw pointerpointer get() const noexceptReturns the managed raw pointer
Check if emptyexplicit operator bool() const noexceptChecks whether an object is held
DereferenceT& operator*() constAccesses the managed object
Member accessT* operator->() constAccesses members via pointer
Array subscriptT& operator[](size_t i) const(Array specialization) Accesses 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 footprint
  • Deterministic destruction: Releases memory immediately when the scope ends, meeting embedded requirements for real-time performance and deterministic memory
  • Perfectly 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


Some content adapted from cppreference.com under CC-BY-SA 4.0 license

Built with VitePress