C++智能指针weak_ptr
学习路线:C++智能指针shared_ptr->C++智能指针unique_ptr->C++智能指针weak_ptr
简介:本文讲解常用的智能指针的用法和原理,包括shared_ptr,unique_ptr,weak_ptr。
概述
weak_ptr设计的目的是为配合 shared_ptr 而引入的一种智能指针来协助 shared_ptr 工作, 它只可以从一个 shared_ptr或另一个 weak_ptr 对象构造, 它的构造和析构不会引起引用记数的增加或减少。
weak_ptr(弱指针),主要用来解决shared_ptr的环型依赖问题.
学习代码
互相引用导致的环形依赖问题
#include<memory>
#include<iostream>
#include<string>
using namespace std;
struct School; // 向前引用
struct Teacher{
string name;
shared_ptr<School> school;
~Teacher(){
cout << "Teacher Destructed" << endl;
}
};
struct School{
string name;
shared_ptr<Teacher> school;
~School(){
cout << "School Destructed" << endl;
}
};
int main()
{
auto p1 = make_shared<Teacher>();
auto p2 = make_shared<School>();
p1->school = p2;
p2->school = p1;
return 0;
}
运行结果:
环形依赖问题导致,shared_ptr的引用计数不能降为0的问题,两个对象函数之间相互引用导致,引用计数不能降为0,然后就无法释放创建的两个对象,所以下面的输出就是没有输出。

解决办法
#include<memory>
#include<iostream>
#include<string>
using namespace std;
struct School; // 向前引用
struct Teacher{
string name;
weak_ptr<School> school; // 这里改成弱指针
~Teacher(){
cout << "Teacher Destructed" << endl;
}
};
struct School{
string name;
shared_ptr<Teacher> school;
~School(){
cout << "School Destructed" << endl;
}
};
int main()
{
auto p1 = make_shared<Teacher>();
auto p2 = make_shared<School>();
p1->school = p2;
p2->school = p1;
return 0;
}
运行结果






![[附源码]Node.js计算机毕业设计电子购物商城Express](https://img-blog.csdnimg.cn/2d82967ef9b444ff95f354b9a19fb367.png)
![[附源码]计算机毕业设计电商小程序Springboot程序](https://img-blog.csdnimg.cn/dba09e01e9ae47a2bc1e8c01bd30bdcc.png)







![[附源码]计算机毕业设计的云网盘设计Springboot程序](https://img-blog.csdnimg.cn/4f5351e6f24a4d069d2c39ddd9fd0726.png)



