c++ shared_ptr的错误用法之cycle引用
2017-05-13 12:16
239 查看
#include <iostream> #include <memory> #include <string> #include <vector> using namespace std; class Person { public: string name; shared_ptr<Person> monther; shared_ptr<Person> father; vector<shared_ptr<Person>> kids; public: Person(const string& n,shared_ptr<Person> m = nullptr,shared_ptr<Person> f = nullptr):name(n),monther(m),father(f) {} ~Person() { cout << "delete " << name << endl; system("pause"); } }; shared_ptr<Person> initFamily(const string& name) { shared_ptr<Person> mom(new Person(name + "'s monther")); shared_ptr<Person> dad(new Person(name + "'s father")); shared_ptr<Person> kid(new Person(name, mom, dad)); mom->kids.push_back(kid);//++use_count; dad->kids.push_back(kid);//++use_count; return kid; //++use_count; }//--use_count; int main() { shared_ptr<Person> kid = initFamily("Marco");//++use_count; cout << kid.use_count() << endl; //因shared_ptr形成cycle无法释放,故无法调用析构函数 //下面的system("pause")则必须有,否则会一闪而过 system("pause"); return 0; }
//解决办法:使用weak_ptr
#include <iostream> #include <memory> #include <string> #include <vector> using namespace std; class Person { public: string name; shared_ptr<Person> monther; shared_ptr<Person> father; vector<weak_ptr<Person>> kids; public: Person(const string& n, shared_ptr<Person> m = nullptr, shared_ptr<Person> f = nullptr):name(n),monther(m),father(f) { } ~Person() { cout << "detele " << name << endl; } }; shared_ptr<Person> initFamily(const string& name) { shared_ptr<Person> mom(new Person(name + "'s monther")); shared_ptr<Person> dad(new Person(name + "'s father")); shared_ptr<Person> kid(new Person(name, mom, dad)); weak_ptr<Person> w_kid(kid); mom->kids.push_back(w_kid); dad->kids.push_back(w_kid); return kid; } int main() { shared_ptr<Person> p = initFamily("Marco"); cout << p.use_count() << endl; cout << "the kid is " << p->name << endl; cout << "the kid's monther " << p->monther->name << endl; cout << "the kid's father " << p->father->name << endl; for (auto &v : p->monther->kids) if (!v.expired()) cout << v.lock()->name << endl; //析构函数会调用,则下面system("pause")不需要添加 //另外通过命令行编译更直观 //system("pause"); return 0; }
相关文章推荐
- c++中关于智能指针std::tr1::shared_ptr的用法
- c++:分析智能指针shared_ptr存在的循环引用的缺陷
- std::shared_ptr 和 std::weak_ptr的用法以及引用计数的循环引用问题
- std::shared_ptr 和 std::weak_ptr的用法以及引用计数的循环引用问题
- C++应用系列:用智能指针shared_ptr中引用计数思想进行动态内存管理
- C++智能指针(三):weak_ptr--解决shared_ptr循环引用问题
- std::shared_ptr 和 std::weak_ptr的用法以及引用计数的循环引用问题
- C++中的智能指针(1):shared_ptr 的介绍和用法
- std::shared_ptr 和 std::weak_ptr的用法以及引用计数的循环引用问题
- C++ shared_ptr的用法
- std::shared_ptr 和 std::weak_ptr的用法以及引用计数的循环引用问题
- C++ std::tr1::shared_ptr使用
- 复习C++:引用的一些用法
- C++ 引用的作用和用法
- C++中的&表示引用与取址的用法
- 在smart_ptr中处理引用计数时使用swap概念(boost::shared_ptr.hpp)
- 【转】C++ std::tr1::shared_ptr使用
- 智能指针 shared_ptr 的用法误区.
- C++ 引用的作用和用法
- c++中参数传递的三种方式,以及用法。传值,传址,传引用