unique_ptr
独占指针,只能通过move转移控制权
shared_ptr
共享指针(带计数)
weak_ptr
弱指针,解决循环引用
不具有普通指针的行为,没有重载operator*和operator->
没有共享资源,它的构造不会引起引用计数增加
用于协助shared_ptr来解决循环引用问题
可以从一个shared_ptr或者另外一个weak_ptr对象构造,进而可以间接获取资源的弱共享权。
一个例子
class alpha;
class child {
public:
int val;
weak_ptr<alpha> aptr;
child(int x) { val = x;}
};
class alpha {
public:
shared_ptr<child> cptr;
};
用法
shared_ptr<alpha> t1 = make_shared<alpha>();
t1->cptr = make_shared<child>(1);
cout << t1->cptr->val<<endl;
auto t2 = make_shared<alpha>();
t1->cptr->aptr = t2;
t2->cptr = make_shared<child>(2);
cout << t1->cptr->aptr.lock()->cptr->val;
shared_ptr可以赋值给weak_ptr
通过weak_ptr访问指向的地址数据需要通过.lock()接口(返回的是shared_ptr)