C++ 智能指针
本质:类对象
思想:利用类对象的析构函数来实现当智能指针过期时自动删除其指向的内存
种类:auto_ptr(C++ 98), shared_ptr, unique-ptr, weak_ptr
头文件:memory
命名空间: std
1.使用
以auto_ptr为例:
template<class X> class auto_ptr {
public:
explicit auto_ptr(X* p = 0);
/*......*/
};
int a = 1;
int *b = new int(1);
auto_ptr<int> ap1(new int(1)); //Yes
auto_ptr<int> ap2 = b; //No explicit禁止隐式转换,vs编译报错
auto_ptr<int> ap3(&a); //No 编译不报错,但是在ap3过期后, a位于栈中,ap3的析构函数用delete删除时会报错
auto_ptr<int> ap4(b); //Yes
2.auto_ptr存在的问题
int* i = new int(0);
auto_ptr<int> ap1(i);
auto_ptr<int> ap2(i);
a1, a2 都指向i所指向的内存, 在ap1过期,和ap2过期后会被删除两次从而报错。这也是auto_ptr在C++98后被淘汰的原因
3.unique_ptr 和 shared_ptr
之前auto_ptr存在的问题可以通过重载=运算符, 使其深拷贝来解决, unique_ptr 和 shared_ptr则是提供了另外两种解决思路:
1. unique_ptr,对于特定的对象,只有一个智能指针。
2. shared_ptr,则是增加一个计数器,赋值时计数器+1, 过期时计数器-1,这样只有在最后一个指针过期时才会delete对象
int* i = new int(0);
unique_ptr<int> ap1(i);
unique_ptr<int> ap2;
ap2 = ap1; // 编译出错
unique_ptr<int> ap3(i); //运行出错