在C++11标准之前的C98标准中,STL里面只有auto_ptr这一种智能指针。
而在C++11标准中除了auto_ptr还有如下三种:
unique_ptr
smart pointer with unique object ownership semantics
只能有一个主人的指针,可以做为STL容器的元素 (弥补了auto_ptr不能作为容器元素的缺点)
shared_ptr
smart pointer with shared object ownership semantics
可共享的指针,可以做为STL容器的元素
weak_ptr
weak reference to an object managed by std::shared_ptr
弱引用指针
auto_ptr 通过复制构造或者通过=赋值后,原来的auto_ptr对象就报废了,所有权转移到新的对象中去了。
shared_ptr 可以让多个智能指针对象同时拥有某一块内存的访问权。
假如我们不希望多个内存块被多个智能指针对象共享,同时又不会像auto_ptr那样不知不觉的就让原来的auto_ptr对象失效, 这个时候就要使用unique_ptr了
特点:
- 同时只能有一个智能指针对象指向某块内存
- 无法进行复制构造与赋值操作
- 可以进行移动构造和移动赋值操作
- 可做为容器元素
使用例子:
//智能指针的创建
unique_ptr<int> u_i; //创建“空智能指针”
u_i.reset(new int(3)); //"绑定”动态对象
unique_ptr<int> u_i2(new int(4));//创建时指定动态对象
//所有权的变化
int *p_i = u_i2.release(); //释放所有权
unique_ptr<string> u_s(new string("abc"));
unique_ptr<string> u_s2 = std::move(u_s); //所有权转移(通过移动语义),u_s所有权转移后,变成“空指针”
u_s2=nullptr;//显式销毁所指对象,同时智能指针变为空指针。与u_s2.reset()等价