shared_ptr 的循环依赖问题
发布时间:2020-12-14 05:02:06 所属栏目:百科 来源:网络整理
导读:#include memory#include iostreamusing namespace std;struct A;struct B;struct A { shared_ptrB B_ptr; A() { cout "construct A" endl; } ~A() { cout "destory A" endl; }};struct B { shared_ptrA A_ptr; B() { cout "construct B" endl; } ~B() { cou
#include <memory> #include <iostream> using namespace std; struct A; struct B; struct A { shared_ptr<B> B_ptr; A() { cout << "construct A" << endl; } ~A() { cout << "destory A" << endl; } }; struct B { shared_ptr<A> A_ptr; B() { cout << "construct B" << endl; } ~B() { cout << "destroy B" << endl; } }; void loop() { shared_ptr<A> ap(new A()); // ap 的引用计数是1 shared_ptr<B> bp(new B()); // bp 的引用计数是1 cout << ap.use_count() << endl; cout << bp.use_count() << endl; ap -> B_ptr = bp; //ap的引用计数是2 bp -> A_ptr = ap; //bp的引用计数是2 cout << ap.use_count() << endl; cout << bp.use_count() << endl; // 将 ap 所指向的对象记作 Aobj,将bp所指向的对象记作 Bobj。 // 准备析构 bp,此时Bobj的use_count 是 2,因此析构bp不会销毁 Bobj,而是使 Bobj的use_count变为1。 // 注意:此时 Aobj 的 use_count 是 2,一个来自 ap,另一个来自 Bobj.A_ptr(记住:Bobj 并未被销毁) // 同理析构 ap 只会把 ap的use_count变为 1 而不会销毁 Aobj。这样就造成内存泄漏了。 } int main() { loop(); return 0; } ReferencesCircular dependency issues with std::shared_ptr,and std::weak_ptr (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
相关内容
- cocos2d-js 重新require JS文件
- c# – 通过获取原始实体Linq到Collections Group
- ruby-on-rails – 使用Ruby on Rails Twitter Gem在twitter
- ruby-on-rails – 使用Devise进行身份验证失败的自定义XML响
- 悉数11种主流NoSQL文档型数据库
- ruby-on-rails – 如何使用rmagick将动态文本附加到图像?
- 集成vue到jquery/bootstrap项目的方法
- ruby-on-rails-3.1 – 如何在Rails 3.1中响应多个对象
- 受保护的枚举在C#中不可能
- c# – 使用动态内容创建局部视图
推荐文章
站长推荐
热点阅读