一、产生的原因:
unique_ptr的产生,就是为了解决,raw pointer 的new和delete配对使用问题。对于raw pointer来说,在new了之后,在delete之前往往会出现程序异常,进而导致delete没有被释放,如此以来就会产生内存泄漏。引入了unique_ptr之后,可以有效的减轻C++程序员对于raw pointer的使用负担。参考官方文档:
std::unique_ptr is a smart pointer that owns and manages another object through a pointer and disposes of that object when the unique_ptr goes out of scope.
https://en.cppreference.com/w/cpp/memory/unique_ptr
二、特性:
也正是因为上面的原因,unique_ptr具有两个特性:
特性1: 替代raw pointer,来封装对象,进行操作,不需要考虑内存泄漏,参考官方文档。
The object is disposed of, using the associated deleter when either of the following happens:
the managing
unique_ptr
object is destroyedthe managing
unique_ptr
object is assigned another pointer via operator= or reset().https://en.cppreference.com/w/cpp/memory/unique_ptr
特性2: 具有ownership transfer的能力, 参考官方文档。
Only non-const unique_ptr
can transfer the ownership of the managed object to another unique_ptr
. If an object's lifetime is managed by a const std::unique_ptr, it is limited to the scope in which the pointer was created.
std::unique_ptr
is commonly used to manage the lifetime of objects, including:
-
providing exception safety to classes and functions that handle objects with dynamic lifetime, by guaranteeing deletion on both normal exit and exit through exception
-
passing ownership of uniquely-owned objects with dynamic lifetime