C++智能指针

unique_ptr

原型

`
template<
class T,
class Deleter = std::default_delete

class unique_ptr;

template <
class T,
class Deleter

class unique_ptr<T[], Deleter>;
`

以下英文抄自https://en.cppreference.com/w/cpp/memory/unique_ptr。面试复习备份。

具体解释

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.

The object is disposed of using the associated deleter when either of the following happens:
*the managing unique_ptr object is destroyed
*the managing unique_ptr object is assigned another pointer via operator= or reset().

基本API

class A{ public: A(int _val) : val(_val){}; private: int val; } //创建 auto ptr = make_unqie<A>(1); auto ptr1 = unique_ptr<A>(new A(2)); //赋值 ptr = make_unqie<A>(3); ptr.reset(new A(4); // reset形参为pointer ptr.swap(ptr1); // operator on the pointer A * a = ptr.get();// ptr仍持有该对象 A *b = ptr.release(); // ptr 释放控制权,不会调用pointer的析构 delete b; // work as raw ptr int a = ptr->val; A &a = *ptr;

Note

*unique_ptr独占整个对象,所以在赋值时需要移动语义保证只有一个unique_ptr持有指向的对象
*unique_ptr大小和原生指针一样
*可指定deleter。不同deleter,相同T的unique_ptr 具有相同类型
*Only non-const unique_ptr can transfer the ownership of the managed object to another unique_ptr

common use

*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 into functions
*acquiring ownership of uniquely-owned objects with dynamic lifetime from functions
*as the element type in move-aware containers, such as std::vector, which hold pointers to dynamically-allocated objects (e.g. if polymorphic behavior is desired)

unqiue_ptr 指向派生

If T is a derived class of some base B, then std::unique_ptr is implicitly convertible to std::unique_ptr. The default deleter of the resulting std::unique_ptr will use operator delete for B, leading to undefined behavior unless the destructor of B is virtual. Note that std::shared_ptr behaves differently: std::shared_ptr will use the operator delete for the type T and the owned object will be deleted correctly even if the destructor of B is not virtual.

shared_ptr

weak_ptr

posted @ 2018-11-28 17:09  hxidkd  阅读(187)  评论(0编辑  收藏  举报