C++ 智能指针 shared_ptr unique_ptr weak_ptr
2014-04-02 19:53
555 查看
和普通指针区别: 能够自动释放所指向的对象shared_ptr unique_ptr weak_ptr
shared_ptr unique_ptr 常用方法
weak_ptr 参考:http://www.cnblogs.com/TenosDoIt/p/3456704.html
一般用于shared_ptr 引起的循环引用(Objective-c 也有这种处理方法) 使用weak_ptr 来解决,使用weak_ptr引用计数不增加。 他需要shared_ptr来初始化,而且也不能通过他直接访问对象(有可能访问的对象已经被释放不存在了),可以通过weak_lock()来访问(他会检查访问的对象是否存在,并返回一个shared_ptr)。
pb_; 改成weak_ptr<B>
pb_; 就能解决此问题。
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_; 就能解决此问题。
相关文章推荐
- C++中的智能指针——auto_ptr, unique_ptr, shared_ptr和weak_ptr
- C++ 智能指针shared-ptr,unique_ptr和weak-ptr
- [置顶] 从零开始学C++之boost库(一):详解 boost 库智能指针(scoped_ptr<T> 、shared_ptr<T> 、weak_ptr<T> 源码分析)
- C++11新特性之智能指针(shared_ptr/unique_ptr/weak_ptr)
- C++智能指针:auto_ptr、shared_ptr、weak_ptr等
- 详解C++各种智能指针: auto_ptr, shared_ptr, weak_ptr, scoped_ptr
- stl中auto_ptr,unique_ptr,shared_ptr,weak_ptr四种智能指针使用总结
- c++ 智能指针- shared_ptr和weak_ptr
- C++智能指针(scoped_ptr<T> 、shared_ptr<T> 、weak_ptr<T> )
- C++ 智能指针(shared_ptr/weak_ptr)源码分析
- C++14 智能指针unique_ptr、shared_ptr、weak_ptr
- 实战c++中的智能指针unique_ptr系列--通过unique_ptr对shared_ptr进行初始化
- stl中auto_ptr,unique_ptr,shared_ptr,weak_ptr四种智能指针使用总结
- 实战c++中的智能指针unique_ptr系列--通过unique_ptr对shared_ptr进行初始化
- C++学习之智能指针--auto_ptr、scoped_ptr、scoped_array、shared_ptr、shared_array、weak_ptr
- c++11 智能指针 unique_ptr、shared_ptr与weak_ptr
- [置顶] 从零开始学C++之boost库(一):详解 boost 库智能指针(scoped_ptr<T> 、shared_ptr<T> 、weak_ptr<T> 源码分析)
- C++总结8——shared_ptr和weak_ptr智能指针
- C++11新特性之智能指针(shared_ptr/unique_ptr/weak_ptr)
- auto_ptr, unique_ptr, shared_ptr and weak_ptr智能指针讲解