zl程序教程

您现在的位置是:首页 >  后端

当前栏目

C++智能指针weak_ptr

C++智能 指针 ptr weak
2023-09-14 09:14:24 时间

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;
}

运行结果
在这里插入图片描述