std::unique_ptr是C++11提供的用于管理资源的智能指针,它的一个很重要的特性就是独享被管理对象指针所有权。也就是说,unique_ptr对象无法被赋值,只能移动。如下:
auto p = std::make_unique<int>();
auto x = p; // 编译报错
auto q = std::move(p); // 所有权转移,q指向p之前指向的对象,p变成nullptr
unique_ptr的定义如下:
template<
class T,
class Deleter = std::default_delete<T>
> class unique_ptr;
template<
class T,
class Deleter
> class unique_ptr<T[], Deleter>;
注意模板类的第二个类型Deleter,该类型可以是缺省的,也可以是一个callable,用于当unique_ptr对象被析构时触发。如下:
std::unique_ptr<int, std::function<void(int*)>> p(new int, [](int* ptr)
{
std::cout << "destroying from a custom deleter..." << std::endl;
delete ptr;
});
参考:https://en.cppreference.com/w/cpp/memory/unique_ptr