CPP 智能指针总结分享

本文介绍了C++的智能指针,包括shared_ptr、unique_ptr和weak_ptr的用途、常见函数及注意事项。强调了智能指针在防止内存泄漏、管理共享资源上的作用,并通过与垃圾回收的对比,阐述了智能指针的生命周期管理策略。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Table of Contents

  1. 智能指针 - smart pointer
  2. 疑问暂存
  3. 作用
  4. shared_ptr
    1. 常用函数
      1. 构造 shared_ptr
      2. 谨慎使用原始指针
      3. 指定删除器
      4. 注意问题
  5. unique_ptr
  6. weak_ptr
    1. 解决的问题
    2. 设计目的
    3. 使用函数

本专栏知识点是通过<零声教育>的系统学习,进行梳理总结写下文章,对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

智能指针用来确保一个对象可在没有引用后被删除。

疑问暂存

  1. 为什么感觉和 rust 的 copy,move 语义很像; cpp-vs-rust-ownership

  2. 当 shared_ptr ref_count 计数到 0 开始调用析构的行为,与 GC 的对比

    https://stackoverflow.com/questions/4663385/garbage-collection-vs-shared-pointers

    最主要的区别在与资源被释放的时间;

    • GC 可能发生在资源紧缺时,并且会要求程序暂停
    • shared pointers 紧跟在 reference count 缩减到 0 时发生
  3. GC 一定是存在于语言 runtime 上吗?

作用

  1. 防止内存泄漏:无需手动释放,可自动释放堆上内存
  2. 共享所有权指针的传播和释放,比如多线程使用同一个对象时析构问题

C++11 支持如下三种智能指针:shared_ptr,unique_ptr, weak_ptr,其中三者特点体现在所有权问题上。

shared_ptr

https://en.cppreference.com/w/cpp/memory/shared_ptr

img

shared_ptr 包含有两部分:

  1. 指向堆上对象的裸指针,raw_ptr
  2. 指向控制块,其中包含一个 reference count、一个 weak count

常用函数

  1. std::make_shared 创建对象 T,并由 std::shared_ptr 封装起来
  2. std::shared_ptr::get 返回存储的指针,
  3. std::shared_ptr::reset 重置管理的对象
  4. 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 的强引用计数
  5. std::shared_ptr::unique 若 use_count() 为 1 则返回 true,否则 false
#include <iostream>
#include <memory>

void fun(std::shared_ptr<int> s
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值