unique_ptr最先在boost中被定义,后来被C++标准委员会选中为C++11的feature之一。
std::unique_ptr is a smart pointer that retains sole ownership of an object through a pointer and destroys that object when the unique_ptr goes out of scope. No two unique_ptr instances can manage the same object.
The object is destroyed and its memory deallocated when either of the following happens:
- unique_ptr managing the object is destroyed
- unique_ptr managing the object is assigned another pointer via operator= or reset().
The object is destroyed using a potentially user-supplied deleter by calling Deleter(ptr). The deleter calls the destructor of the object and dispenses the memory.
A unique_ptr may also own no objects, in which case it is called empty.
There are two versions of std::unique_ptr:
- Manages the lifetime of a single object (e.g. allocated with new)
- Manages the lifetime of a dynamically-allocated array of objects (e.g. allocated with new[])
The class satisfies the requirements of MoveConstructible and MoveAssignable, but not the requirements of either CopyConstructible or CopyAssignable. [see C++11 Concepts]