正常
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.
Header
#include <memory>
Core API Cheat Sheet
| Operation | Signature | Description |
|---|---|---|
| Create object | template<class T> unique_ptr<T> make_unique(Args&&... args) | (C++14) Create unique_ptr in an exception-safe manner |
| Constructor | constexpr unique_ptr(pointer p = pointer()) | Take ownership of a raw pointer |
| Destructor | ~unique_ptr() | Destroy the managed object |
| Release ownership | pointer release() noexcept | Relinquish ownership and return the raw pointer |
| Reset pointer | void reset(pointer p = pointer()) | Destroy current object and take ownership of a new pointer |
| Get raw pointer | pointer get() const noexcept | Return the managed raw pointer |
| Check if empty | explicit operator bool() const noexcept | Determine if an object is held |
| Dereference | T& operator*() const | Access the managed object |
| Member access | T* operator->() const | Access members via pointer |
| Array subscript | T& 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
| 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