智能指针weak_ptr解决循环依赖问题
2016-09-28 15:11
651 查看
#include <iostream> #include <memory> class Woman; class Man{ private: std::weak_ptr<Woman> _wife; //std::shared_ptr<Woman> _wife; public: void setWife(std::shared_ptr<Woman> &woman){ _wife = woman; } void doSomthing(){ if (_wife.lock()){ } } ~Man(){ std::cout << "kill man\n"; } }; class Woman{ private: //std::weak_ptr<Man> _husband; std::shared_ptr<Man> _husband; public: void setHusband(std::shared_ptr<Man> &man){ _husband = man; } ~Woman(){ std::cout << "kill woman\n"; } }; int main() { std::shared_ptr<Man> m(new Man()); std::shared_ptr<Woman> w(new Woman()); if (m && w) { m->setWife(w); w->setHusband(m); } return 0; }
相关文章推荐
- C++智能指针(三):weak_ptr--解决shared_ptr循环引用问题
- 【C++】智能指针简述(五):解决循环引用的weak_ptr
- weak_ptr 弱引用打破智能指针中循环引用造成的内存泄露
- weak_ptr解决循环引用问题demo
- 标准库里的weak_ptr如何解决循环引用所带来的问题
- std::shared_ptr 和 std::weak_ptr的用法以及引用计数的循环引用问题
- 解决rpm包安装时的循环依赖问题
- Boost智能指针——scoped_ptr、shared_ptr、weak_ptr、intrusive_ptr
- auto_ptr智能指针问题
- sql之解决数据库表的循环依赖问题
- boost库在工作(11)引用计数的智能指针weak_ptr
- [6] 智能指针boost::weak_ptr
- 解决RPM包循环依赖的问题
- 详解 boost 库智能指针(scoped_ptr<T> 、shared_ptr<T> 、weak_ptr<T> 源码分析)
- C++11智能指针之shared_ptr、weak_ptr
- boost中的智能指针的使用-------解决C++内存问题的最优方案
- Boost智能指针——weak_ptr vs shared_ptr
- 智能指针boost::weak_ptr
- 智能指针weak_ptr
- boost库在工作(11)引用计数的智能指针weak_ptr