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.
Header
#include <memory>
Core API Quick Reference
| Operation | Signature | Description |
|---|---|---|
| Create object | template<class T> unique_ptr<T> make_unique(Args&&... args) | (C++14) Exception-safe creation of unique_ptr |
| Constructor | constexpr unique_ptr(pointer p = pointer()) | Takes ownership of a raw pointer |
| Destructor | ~unique_ptr() | Destroys the managed object |
| Release ownership | pointer release() noexcept | Relinquishes ownership and returns the raw pointer |
| Reset pointer | void reset(pointer p = pointer()) | Destroys the current object and takes ownership of a new pointer |
| Get raw pointer | pointer get() const noexcept | Returns the managed raw pointer |
| Check if empty | explicit operator bool() const noexcept | Checks whether an object is held |
| Dereference | T& operator*() const | Accesses the managed object |
| Member access | T* operator->() const | Accesses members via pointer |
| Array subscript | T& 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
| GCC | Clang | MSVC |
|---|---|---|
| 4.4 | 2.9 | 2010 |
See Also
Some content adapted from cppreference.com under CC-BY-SA 4.0 license