C++11 智能指针unique_ptr
2016-12-13 16:51
281 查看
在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了
特点:
1. 同时只能有一个智能指针对象指向某块内存
2. 无法进行复制构造与赋值操作
3. 可以进行移动构造和移动赋值操作
4. 可做为容器元素
使用例子:
而在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了
特点:
1. 同时只能有一个智能指针对象指向某块内存
2. 无法进行复制构造与赋值操作
3. 可以进行移动构造和移动赋值操作
4. 可做为容器元素
使用例子:
//智能指针的创建 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()等价
相关文章推荐
- C++11智能指针之unique_ptr
- C++11引入智能指针std::unique_ptr
- (转载)【C++11新特性】 C++11智能指针之unique_ptr
- 【C++11新特性】 C++11智能指针之unique_ptr
- C++11教程1 智能指针——unique_ptr
- C++11智能指针之std::unique_ptr
- C++11新特性之智能指针(shared_ptr/unique_ptr/weak_ptr)
- C++11智能指针之unique_ptr
- C++11 unique_ptr独占的智能指针
- c++11:智能指针之unique_ptr
- C++11智能指针之unique_ptr
- C++11智能指针之unique_ptr
- 【C++11新特性】 C++11智能指针之unique_ptr
- c++11 智能指针 unique_ptr、shared_ptr与weak_ptr
- C++11新特性之智能指针(shared_ptr/unique_ptr/weak_ptr)
- C++11智能指针之unique_ptr
- C++11 Intro - C++11智能指针之unique_ptr
- C++11 智能指针——unique_ptr
- c++11之unique_ptr智能指针使用
- C++11智能指针之unique_ptr