东方耀AI技术分享
标题:
问题抛出:智能指针shared_ptr用weak_ptr打破循环引用
[打印本页]
作者:
东方耀
时间:
2021-9-14 18:08
标题:
问题抛出:智能指针shared_ptr用weak_ptr打破循环引用
问题抛出:智能指针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;
}
复制代码
作者:
东方耀
时间:
2021-9-15 09:47
参考这个用法:
http://www.ai111.vip/thread-1261-1-1.html
改进如下:
#include <iostream>
#include <memory>
class Parent; // 前置申明
//weak_ptr只能与shared_ptr结合使用,不能单独使用
typedef std::shared_ptr<Parent> ParentPtr;
typedef std::weak_ptr<Parent> ParentPtr_weak;
class Child{
public:
ParentPtr_weak father; //只用一个即可 打破了循环引用
Child();
~Child();
};
typedef std::shared_ptr<Child> ChildPtr;
typedef std::weak_ptr<Child> ChildPtr_weak;
class Parent{
public:
ChildPtr_weak 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; // 又是用强指针赋值给弱指针
//Object_weak_ptr weak_obj(obj); //一般通过shared_ptr来构建weak_ptr
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;
}
复制代码
作者:
zouqiqi
时间:
2021-11-23 19:28
让天下人人学会人工智能!人工智能的前景一片大好!
欢迎光临 东方耀AI技术分享 (http://www.ai111.vip/)
Powered by Discuz! X3.4