概念:智能指针为了确保申请的资源一定会被释放,实质是在栈上创建对象,利用栈上的对象出了作用域就析构的特点。
分类:
1. 不带引用计数的智能指针:auto_ptr scoped_ptr unique_ptr
2. 带引用计数的智能指针:shared_ptr weak_ptr
auto_ptr
使用方法: 创建
#include <iostream>
#include <memory>
using namespace std;
class A
{
public:
void show()
{
cout<<"A::show"<<endl;
}
private:
int a;
};
int main()
{
auto_ptr<A> a(new A);
A* b = a.get();
return 0;
}
库实现
从上图可以看出 release的删除没有reset删除方便。
代码使用对比
auto_ptr<A> a(new A);
A* p = a.release();
delete p;
auto_ptr<A> b(new A);
b.reset();
auto还提供了赋值运算的重载即
使用
auto_ptr<A> aa;
aa = a;
意思是将a的指向交给给aa,a置空。在使用时一不小心就使用了赋值后的a,导致崩溃。
unique_ptr
和auto_ptr类似,不过其operator= 和 拷贝被设置为私有的。
shared_ptr和weak_ptr
shared_ptr和weak_ptr是带引用计数的智能指针。
shared_ptr的实现多了一个引用计数,放增加一个共享对象就将其引用计数+1,析构-1,直到引用计数为0时才进行销毁。所以在多线程中,共享一个对象使用shared_ptr在好不过。
不过shared_ptr容易引起交叉引用问题,解决方案:降为weak_ptr即可
weak_ptr在使用时其引用计数总为1,当增加指向时引用计数也不加1,weak_ptr是相对于shared_ptr设计的,有时候只注重与共享对象,而不关注引用计数,且weak_ptr常用来确认对象是否还存在。weak_ptr可以同过lock方法提升为shared_ptr。