C++ 智能指针 shared_ptr unique_ptr weak_ptr
来源:互联网 发布:ug nx11编程新功能 编辑:程序博客网 时间:2024/06/07 23:29
和普通指针区别: 能够自动释放所指向的对象shared_ptr unique_ptr weak_ptr
shared_ptr unique_ptr 常用方法
#include <iostream>using namespace std;int main(int argc, const char * argv[]){ shared_ptr<string>p1(new string("shared")); shared_ptr<string>p2; cout<<p1.use_count()<<endl; //1 cout<<p2.use_count()<<endl; //0 p2 = p1; cout<<p1.use_count()<<endl; //2 cout<<p2.use_count()<<endl; //2 unique_ptr<string>p3(new string("unique")); unique_ptr<string>p4(p3.release()); //释放对象所有权 不能使用直接赋值或拷贝 cout<<*p4<<endl; //unique return 0;}
weak_ptr 参考:http://www.cnblogs.com/TenosDoIt/p/3456704.html
一般用于shared_ptr 引起的循环引用(Objective-c 也有这种处理方法) 使用weak_ptr 来解决,使用weak_ptr引用计数不增加。 他需要shared_ptr来初始化,而且也不能通过他直接访问对象(有可能访问的对象已经被释放不存在了),可以通过weak_lock()来访问(他会检查访问的对象是否存在,并返回一个shared_ptr)。
class B;class A{public: shared_ptr<B> pb_; ~A() { cout<<"A delete\n"; }}; class B { public: shared_ptr<A> pa_; ~B() { cout<<"B delete\n"; } }; void fun() { shared_ptr<B> pb(new B()); shared_ptr<A> pa(new A()); pb->pa_ = pa; pa->pb_ = pb; cout<<pb.use_count()<<endl; //2 cout<<pa.use_count()<<endl; //2 } int main() { fun(); return 0; }此时引起循环引用,如果把A的shared_ptr<B> pb_; 改成weak_ptr<B> pb_; 就能解决此问题。
0 0
- 【C++】智能指针auto_ptr/unique_ptr/shared_ptr/weak_ptr!!!
- C++ 智能指针 shared_ptr unique_ptr weak_ptr
- C++11 智能指针 unique_ptr shared_ptr weak_ptr
- 智能指针shared_ptr、weak_ptr、unique_ptr总结
- C++智能指针 shared_ptr,unique_ptr和weak_ptr
- C++14 智能指针unique_ptr、shared_ptr、weak_ptr
- C++11新特性之智能指针(shared_ptr/unique_ptr/weak_ptr)
- auto_ptr, unique_ptr, shared_ptr and weak_ptr智能指针讲解
- C++11 智能指针std::shared_ptr/std::unique_ptr/std::weak_ptr
- 智能指针--shared_ptr&&weak_ptr
- stl中auto_ptr,unique_ptr,shared_ptr,weak_ptr四种智能指针使用总结
- C++中的智能指针——auto_ptr, unique_ptr, shared_ptr和weak_ptr
- 智能指针---shared_ptr和weak_ptr
- Boost智能指针shared_ptr、weak_ptr
- 智能指针--scoped_ptr shared_ptr weak_ptr
- shared_ptr,weak_ptr,unique_ptr
- C++:智能指针-TR1的shared_ptr和weak_ptr使用介绍
- C++:智能指针-TR1的shared_ptr和weak_ptr使用介绍
- MATLAB的plot函数颜色和线型设定参数
- 第六周项目1-体验常成员函数
- 【游戏课】技术片段之——使用BillBoard技术进行快速绘制
- TCP/IP详解--ICMP 控制报文和差错报文 && Tracerouter 命令的过程
- 等待事件--db file sequential read
- C++ 智能指针 shared_ptr unique_ptr weak_ptr
- Android SparseArray指的是稀疏数组(Sparse array)
- 双击BACK键退出程序
- Intent以及IntentFileter大全
- 类加载器---创建并使用自定义的类加载器
- 文件下载
- Android:异步任务AsyncTask、execute、publishProgress、onProgressUpdate
- PL/SQL Developer小学习
- vs2010 LINK : fatal error LNK1123: 转换到 COFF 期间失败: 文件无效或损坏