C++智能指针weak_ptr

简介: C++智能指针weak_ptr

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

运行结果

相关文章
|
1天前
|
C++ 数据格式
LabVIEW传递接收C/C++DLL指针
LabVIEW传递接收C/C++DLL指针
13 1
|
1天前
|
编译器 C++
C/C++杂谈——指针常量、常量指针
C/C++杂谈——指针常量、常量指针
9 0
|
1天前
|
C++ 编译器
|
1天前
|
存储 安全 程序员
C++:智能指针
C++:智能指针
20 5
|
1天前
|
存储 安全 C++
深入理解C++中的指针与引用
深入理解C++中的指针与引用
11 0
|
1天前
|
算法 C++
【C++入门到精通】智能指针 shared_ptr循环引用 | weak_ptr 简介及C++模拟实现 [ C++入门 ]
【C++入门到精通】智能指针 shared_ptr循环引用 | weak_ptr 简介及C++模拟实现 [ C++入门 ]
12 0
|
1天前
|
安全 算法 数据安全/隐私保护
【C++入门到精通】智能指针 shared_ptr 简介及C++模拟实现 [ C++入门 ]
【C++入门到精通】智能指针 shared_ptr 简介及C++模拟实现 [ C++入门 ]
13 0
|
1天前
|
存储 算法 安全
【C++入门到精通】智能指针 auto_ptr、unique_ptr简介及C++模拟实现 [ C++入门 ]
【C++入门到精通】智能指针 auto_ptr、unique_ptr简介及C++模拟实现 [ C++入门 ]
13 0
|
1天前
|
安全 算法 IDE
【C++入门到精通】智能指针 [ C++入门 ]
【C++入门到精通】智能指针 [ C++入门 ]
10 0
|
1天前
|
C语言
C语言:数组和指针笔试题解析(包括一些容易混淆的指针题目)
C语言:数组和指针笔试题解析(包括一些容易混淆的指针题目)