On this page
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
- Default smart pointer in modern C++: Zero runtime overhead compared to a raw pointer, move-only (cannot be copied accidentally), and automatically deletes on scope exit.
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
- tuts/cpp/builtins/move_semantics
- tuts/cpp/builtins/new_and_delete
- tuts/cpp/builtins/nullptr
- tuts/cpp/builtins/raii_and_destructors
- tuts/cpp/stdlib/memory
- tuts/cpp/stdlib/memory/auto_ptr
- tuts/cpp/stdlib/memory/make_unique
- tuts/cpp/stdlib/memory/shared_ptr
- tuts/cpp/tutorials/raii_and_rule_of_zero_resource_wrapper
Related notes
- tuts/cpp/stdlib/memory/make_unique Linked here; links to this page; shared tags: #cpp, #memory, #prog, #stdlib, #tier
- tuts/cpp/stdlib/memory/shared_ptr Linked here; links to this page; shared tags: #cpp, #memory, #prog, #stdlib, #tier
- tuts/cpp/stdlib/memory Linked here; links to this page; shared tags: #cpp, #memory, #prog, #stdlib
- tuts/cpp/builtins/move_semantics Linked here; links to this page; shared tags: #cpp, #prog, #tier
- tuts/cpp/builtins/raii_and_destructors Linked here; links to this page; shared tags: #cpp, #prog, #tier
- tuts/cpp/stdlib/memory/auto_ptr links to this page; shared tags: #cpp, #memory, #prog, #stdlib, #tier
- tuts/cpp/builtins/new_and_delete links to this page; shared tags: #cpp, #memory, #prog, #tier
- tuts/cpp/builtins/nullptr links to this page; shared tags: #cpp, #prog, #tier
- tuts/cpp/tutorials/raii_and_rule_of_zero_resource_wrapper links to this page; shared tags: #cpp, #prog, #tier
- tuts/cpp/stdlib/memory/weak_ptr shared tags: #cpp, #memory, #prog, #stdlib, #tier