|
问题抛出:智能指针shared_ptr用weak_ptr打破循环引用
- #include <iostream>
- #include <memory>
- class Parent; // 前置申明
- typedef std::shared_ptr<Parent> ParentPtr;
- class Child{
- public:
- ParentPtr father;
- Child();
- ~Child();
- };
- typedef std::shared_ptr<Child> ChildPtr;
- class Parent{
- public:
- ChildPtr son;
- Parent();
- ~Parent();
- };
- Child::Child(){
- printf("hi child\n");
- }
- Parent::Parent(){
- printf("hi parent\n");
- }
- Child::~Child(){
- printf("bye child\n");
- }
- Parent::~Parent(){
- printf("bye parent\n");
- }
- void test_parent_and_child(){
- ParentPtr p(new Parent());
- ChildPtr c(new Child());
- printf("use_count()=%ld,%ld\n", p.use_count(), c.use_count());
- // 问题出在:下面2行代码中 没有析构 内存泄露
- p->son = c;
- printf("循环指use_count()=%ld,%ld\n", p.use_count(), c.use_count());
- c->father = p;
- printf("循环指use_count()=%ld,%ld\n", p.use_count(), c.use_count());
- // 该语句块结束后 会自动析构 导致use_count会减1 最终引用数都是1 相互等待 进入死循环 导致对象不析构
- }
- int main(){
- printf("问题抛出:智能指针shared_ptr用weak_ptr打破循环引用.cpp\n");
- test_parent_and_child();
- // shared_ptr_with_weak_ptr();
- return 0;
- }
复制代码
|
|