c++智能指针(五)之weak_ptr
2017-12-24 22:27
260 查看
weak_ptr
weak_ptr是一种不控制所指向对象的生存期的智能指针,它指向由一个shared_ptr所管理的对象。将一个weak_ptr绑定到shared_ptr上面不会改变shared_ptr的引用计数。一旦最后一个指向对象的shared_ptr被销毁,对象就会被释放。
创建
auto p = make_shared<int>(42); weak_ptr<int>q(p);//q弱共享p,p的引用计数不会改变
访问
由于对象可能不存在,我们不能使用weak_ptr直接访问对象,而必须调用lock。if (shared_ptr<int> np = q.lock()){//如果np不为空则条件成立 //在if中,np与p共享对象 }
weak_ptr与循环引用
struct A { std::shared_ptr<A> ptr; }; void main() { std::shared_ptr<A> x=std::make_shared<A>(); std::shared_ptr<A> y=std::make_shared<A>(); x->ptr = y; // 这还不算是循环引用 y->ptr = x; // 现在算是循环引用了, x使y保持存活y使x保持存活。他们两个的计数至少为1,永远不会变成0。 }
这个时候,只需要把其中一个shared_ptr改成weak_ptr就可以解决这个问题了。
相关文章推荐
- C++中的智能指针——auto_ptr, unique_ptr, shared_ptr和weak_ptr
- 详解C++各种智能指针: auto_ptr, shared_ptr, weak_ptr, scoped_ptr
- C++智能指针(scoped_ptr<T> 、shared_ptr<T> 、weak_ptr<T> )
- C++:智能指针-TR1的shared_ptr和weak_ptr使用介绍
- 【C++】智能指针简述(五):解决循环引用的weak_ptr
- C++ 智能指针(shared_ptr/weak_ptr)源码分析
- C++智能指针:auto_ptr、shared_ptr、weak_ptr等
- C++智能指针(三):weak_ptr--解决shared_ptr循环引用问题
- C++智能指针--weak_ptr
- C++智能指针--weak_ptr
- C++总结8——shared_ptr和weak_ptr智能指针
- C++智能指针:TR1的 shared_ptr 和 weak_ptr 使用介绍
- C++智能指针 shared_ptr 与 weak_ptr 原理
- [置顶] 从零开始学C++之boost库(一):详解 boost 库智能指针(scoped_ptr<T> 、shared_ptr<T> 、weak_ptr<T> 源码分析)
- [置顶] 从零开始学C++之boost库(一):详解 boost 库智能指针(scoped_ptr<T> 、shared_ptr<T> 、weak_ptr<T> 源码分析)
- C++ 智能指针 shared_ptr unique_ptr weak_ptr
- C++弱引用智能指针weak_ptr的用处
- C++ 智能指针shared-ptr,unique_ptr和weak-ptr
- C++学习之智能指针--auto_ptr、scoped_ptr、scoped_array、shared_ptr、shared_array、weak_ptr
- c++ 智能指针- shared_ptr和weak_ptr