Table of Contents
本专栏知识点是通过<零声教育>的系统学习,进行梳理总结写下文章,对c/c++linux系统提升感兴趣的读者,可以点击链接,详细查看详细的服务:
服务器课程:https://course.0voice.com/v1/course/intro?courseId=5&agentId=0
音视频:https://course.0voice.com/v1/course/intro?courseId=3&agentId=0
dpdk:https://course.0voice.com/v1/course/intro?courseId=4&agentId=0
内核:https://course.0voice.com/v1/course/intro?courseId=2&agentId=0
智能指针 - smart pointer
智能指针用来确保一个对象可在没有引用后被删除。
疑问暂存
-
为什么感觉和 rust 的 copy,move 语义很像; cpp-vs-rust-ownership
-
当 shared_ptr ref_count 计数到 0 开始调用析构的行为,与 GC 的对比
https://stackoverflow.com/questions/4663385/garbage-collection-vs-shared-pointers
最主要的区别在与资源被释放的时间;
- GC 可能发生在资源紧缺时,并且会要求程序暂停
- shared pointers 紧跟在 reference count 缩减到 0 时发生
-
GC 一定是存在于语言 runtime 上吗?
- https://docs.microsoft.com/en-us/dotnet/standard/garbage-collection/fundamentals
- garbage collector for c and cpp: https://zh.wikipedia.org/wiki/貝姆垃圾收集器
作用
- 防止内存泄漏:无需手动释放,可自动释放堆上内存
- 共享所有权指针的传播和释放,比如多线程使用同一个对象时析构问题
C++11 支持如下三种智能指针:shared_ptr,unique_ptr, weak_ptr,其中三者特点体现在所有权问题上。
shared_ptr
shared_ptr 包含有两部分:
- 指向堆上对象的裸指针,raw_ptr
- 指向控制块,其中包含一个 reference count、一个 weak count
常用函数
- std::make_shared 创建对象 T,并由 std::shared_ptr 封装起来
- std::shared_ptr::get 返回存储的指针,
- std::shared_ptr::reset 重置管理的对象
- std::shared_ptr::use_count returns the number of shared_ptr objects referring to the same managed object
Returns the number of different shared_ptr instances (this included) managing the current object. If there is no managed object, 0 is returned.
返回 shared_ptr 的强引用计数 - std::shared_ptr::unique 若 use_count() 为 1 则返回 true,否则 false
#include <iostream>
#include <memory>
void fun(std::shared_ptr<int> s