1.Smartpointer是指针类,会自动释放指针分配的空间
2.包括auto_ptr,shared_ptr,unique_ptr
3.使用方法
(1)包含#include
(2)实例化
auto_ptr
auto_ptr
unique_ptr
shared_ptr
(3)显式类型转换
shared_ptr
double *p_reg=new double;
pd=p_reg;//不可以
pd=shared_ptr
shared_ptr
shared_ptr
(4)
auto_ptr
auto_ptr
vocation=ps;
//上述代码会导致ps指向的内存空间被释放两次,产生错误
解决方法
a.重载赋值运算符使其用深拷贝方式赋值
b.禁止在对象未释放时使用赋值运算符
c.用计数器计数,shared_ptr的实现方式
(5)auto_ptr放弃对象的所有权后会无法访问对象
auto_ptr
auto_ptr
auto_ptr
auto_ptr
pwin=films[0];//赋值后无法使用film[0]访问对象,只能使用Pwin访问对象
}
但shared_ptr
pwin=films[0];//可以
(6)使用move方法实现unique_ptr的转换
using namespace std;
unique_ptr
ps1=demo("Uniquely special");
ps2=move(ps1);
ps1=demo("and more");
cout<<"ps2<<ps1<<endl;
unique_ptr
unique_ptr
return temp;
(7)unique_ptr通常使用new delete但可以有new[]
unique_ptr<double[]>pda(new double(5));
(8)使用auto_ptr,unique_ptr,shared_ptr于用new, delete的地方
只有Unique_ptr有new[],delete[]的用法,其他两者不行。
}