正常
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.
Header
#include <memory>
Core API Cheat Sheet
| Operation | Signature | Description |
|---|---|---|
| Create object | template<class T> unique_ptr<T> make_unique(Args&&... args) | (C++14) Creates a unique_ptr in an exception-safe manner |
| Constructor | constexpr unique_ptr(pointer p = pointer()) | Takes over 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 over a new pointer |
| Get raw pointer | pointer get() const noexcept | Returns the managed raw pointer |
| Check if empty | explicit operator bool() const noexcept | Tests whether it holds an object |
| Dereference | T& operator*() const | Accesses the managed object |
| Member access | T* operator->() const | Accesses members through the pointer |
| Array subscript | T& 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
| GCC | Clang | MSVC |
|---|---|---|
| 4.4 | 2.9 | 2010 |
See Also
Part of the content is referenced from cppreference.com and licensed under CC-BY-SA 4.0