C++中的智能指针

C++中的智能指针

文章目录

  • C++中的智能指针
    • 1.为什么需要智能指针?
    • 2.智能指针的类型
      • 2.1 `std::shared_ptr`
      • 2.2 `std::unique_ptr`
      • 2.3 `std::weak_ptr`
    • Reference

笔者在学习ROS2的过程中,遇到了std::make_shared这种用法,一眼看不懂,才发现笔者对于Cpp 11/17/20的一些新特性还不太了解,于是查找了许多资料写成此文,感谢诸君的分享。

1.为什么需要智能指针?

在C++中,智能指针是一种用于管理动态分配对象的内存工具,它们自动处理内存的分配和释放,并且提供方便的对象所有权管理。说到动态分配内存,很多读者肯定想到了newdelete这两个关键字,智能指针也是类似的内存管理的功能,只不过智能指针会更加安全。举个例子:

#include <iostream>class Foo{
public:Foo(int value) {this-> myval = value;std::cout << "This is construct function!" << std::endl;}~Foo() {std::cout << "This is destruct function!" << std::endl;}int getValue() {return this->myval;}private:int myval = 10;
};int main() {Foo *foo = new Foo(10);delete foo;return 0;
}

Output:

This is construct function!
This is destruct function!

我们正确使用newdelete的情况下,程序正常运行,但如果我们忘记使用delete来恢复空间的时候,会产生如下的异常从而导致内存泄漏

int main() {Foo *foo = new Foo;return 0;
}

如图所示

Image

使用智能指针可以在超过其作用域的时候,自动进行释放而无需手动delete,提升了程序的安全性。举个例子:

#include <iostream>
#include <memory>class Foo{
private:int myval;public:Foo(int value) {this->myval = value;std::cout << "This is construct function!" << std::endl;}~Foo() {std::cout << "This is destruct function!" << std::endl;}int getValue() {return this->myval;}
};int main() {std::unique_ptr<Foo> foo_up(new Foo(42));std::cout << "Call of operator '->' that value of foo is " << foo_up->getValue() << std::endl;std::cout << "Call of operator '*' that value of foo is " << (*foo_up).getValue() << std::endl;return 0;
}   // foo_up is deleted automatically here

Output:

This is construct function!
Call of operator '->' that value of foo is 10
Call of operator '*' that value of foo is 10
This is destruct function!

可见我们使用智能指针std::unique_ptr可以有效地保证安全性,使用智能指针首先需要先包含头文件<memory>。智能指针可以像普通指针一样使用指针运算符(->*)访问封装指针,这是因为智能指针重载了这些运算符。

2.智能指针的类型

一共有四种类型的智能指针std::auto_ptrstd::unique_ptrstd::shared_ptrstd::weak_ptr,其中std::auto_ptr是C++11标准推出的,在C++17已经被弃用了。我们重点关注std::unique_ptrstd::shared_ptrstd::weak_ptr这三个智能指针,使用这三个智能指针需要包含头文件<memory>

在介绍智能指针之前,我们先了解一下引用计数,引用计数的基本思想是对于动态分配的对象,进行引用计数的时候,每当增加一次对同一个对象的引用,那么引用对象的引用计数就会增加一次,每删除一次对同一个对象的引用,引用计数就会删除一次,当一个对象的引用计数为零的时候,就自动释放该对象存放的内存。

2.1 std::shared_ptr

std::shared_ptr是一种智能指针,它能够记录有多少个shared_ptr指向同一个对象,当引用计数为零的时候会将对象自动删除,这样就避免了显示地调用delete

引用计数可以帮助我们不显示调用delete,但是我们还需要显示地调用new进行创建,这是一种不对等的方式,所以在C++ 17中提出了std::make_shared方法来创建智能指针shared_ptrstd::make_shared会分配创建传入参数中的对象,并且返回这个对象类型的std::shared_ptr,这样就避免了我们显示使用new。但我们也可以显示地使用new来构建一个shared_ptr,如下:

auto ptr = std::make_shared<int> (10);		// use 'std::make_shared' to construct a shared_ptr
std::shared_ptr<int> ptr (new int(10));		// use 'new' to construct a shared_ptr

举个基本的使用例子:

#include <iostream>
#include <memory>
void add_(std::shared_ptr<int> p) {(*p) ++;return;
}int main() {// Constructed a std::shared_ptr// std::shared_ptr<int> ptr (new int(10));  // we also can use 'new' to construct a shared_ptrauto ptr = std::make_shared<int> (10);std::cout << *ptr << std::endl;     // cout 10add_(ptr);std::cout << *ptr << std::endl;     // cout 11return 0;
} // The shared_ptr will be destructed here

Output:

10
11

std::shared_ptr顾名思义是可以进行共享的,我们可以将其复制给别的对象,并且曾加一次对原对象的引用,可以使用get()方法来返回一个原始指针,通过reset()方法来减少一个引用计数,即抛弃当前的指针,通过use_count()方法来查看一个对象的引用次数。举个例子:

#include <iostream>
#include <memory>
void add_(std::shared_ptr<int> p) {(*p) ++;return;
}int main() {// Constructed a std::shared_ptrauto ptr1 = std::make_shared<int> (10);// Reference count add twiceauto ptr2 = ptr1;auto ptr3 = ptr1;// Check the value of ptr1,ptr2,ptr3std::cout << "ptr1.use_count() is " << ptr1.use_count() << ", `*ptr1` is "  << *ptr1 << ", address of ptr1 is " << ptr1 << std::endl;std::cout << "ptr2.use_count() is " << ptr2.use_count() << ", `*ptr2` is "  << *ptr2 << ", address of ptr2 is " << ptr2 << std::endl;std::cout << "ptr3.use_count() is " << ptr3.use_count() << ", `*ptr3` is "  << *ptr3 << ", address of ptr3 is " << ptr3 << std::endl;std::cout << std::endl;ptr2.reset();std::cout << "ptr1.use_count() is " << ptr1.use_count() << ", `*ptr1` is "  << *ptr1 << ", address of ptr1 is " << ptr1 << std::endl;std::cout << "ptr2.use_count() is " << ptr2.use_count() << ", address of ptr2 is " << ptr2 << std::endl;        // ptr2 reset, clear the address of ptr2std::cout << "ptr3.use_count() is " << ptr3.use_count() << ", `*ptr3` is "  << *ptr3 << ", address of ptr3 is " << ptr3 << std::endl;std::cout << std::endl;ptr3.reset();std::cout << "ptr1.use_count() is " << ptr1.use_count() << ", `*ptr1` is "  << *ptr1 << ", address of ptr1 is " << ptr1 << std::endl;std::cout << "ptr2.use_count() is " << ptr2.use_count() << ", address of ptr2 is " << ptr2 << std::endl;std::cout << "ptr3.use_count() is " << ptr3.use_count() << ", address of ptr3 is " << ptr3 << std::endl;        // ptr3 reset, clear the address of ptr3std::cout << std::endl;auto original_ptr = ptr1.get();std::cout << "ptr1.use_count() is " << ptr1.use_count() << ", `*ptr1` is "  << *ptr1 << ", address of ptr1 is " << ptr1 << std::endl;std::cout << "ptr2.use_count() is " << ptr2.use_count() << ", address of ptr2 is " << ptr2 << std::endl;std::cout << "ptr3.use_count() is " << ptr3.use_count() << ", address of ptr3 is " << ptr3 << std::endl; std::cout << "*original_ptr is " << *original_ptr << ", address of original_ptr is " << original_ptr <<std::endl;return 0;
} // The shared_ptr will be destructed here

Output:

ptr1.use_count() is 3, `*ptr1` is 10, address of ptr1 is 0x573a3a29eec0
ptr2.use_count() is 3, `*ptr2` is 10, address of ptr2 is 0x573a3a29eec0
ptr3.use_count() is 3, `*ptr3` is 10, address of ptr3 is 0x573a3a29eec0ptr1.use_count() is 2, `*ptr1` is 10, address of ptr1 is 0x573a3a29eec0
ptr2.use_count() is 0, address of ptr2 is 0
ptr3.use_count() is 2, `*ptr3` is 10, address of ptr3 is 0x573a3a29eec0ptr1.use_count() is 1, `*ptr1` is 10, address of ptr1 is 0x573a3a29eec0
ptr2.use_count() is 0, address of ptr2 is 0
ptr3.use_count() is 0, address of ptr3 is 0ptr1.use_count() is 1, `*ptr1` is 10, address of ptr1 is 0x573a3a29eec0
ptr2.use_count() is 0, address of ptr2 is 0
ptr3.use_count() is 0, address of ptr3 is 0
*original_ptr is 10, address of original_ptr is 0x573a3a29eec0

可以看出,使用get()返回一个原始指针并不会减少引用计数。

2.2 std::unique_ptr

std::unique_ptr是一种独占所有权的智能指针,它确保在任何时候都只有一个指针可以管理对象,它不进行共享,也无法复制到其他的unique_ptr,无法通过值传递到函数,只能移动unique_ptr。同样,我们也有两种方式可以来构建unique_ptr

std::unique_ptr<int> ptr = std::make_unique<int>(20);	// use 'std::make_unique' to construct a unique_ptr
std::unique_ptr<int> ptr (new int(20));					// use 'new' to construct a unique_ptr

unique_ptr同样提供了get()方法用于获取原始指针,我们不能将unique_ptr副值给别的变量,但是我们可以使用std::move()方法将其转移给其他的unique_ptr,举个例子:

#include <iostream>
#include <memory>class Foo {
public:Foo(int value) {this-> myval = value;std::cout << "Foo::Foo" << std::endl;}~Foo() {std::cout << "Foo::~Foo" << std::endl;}int myval;void printval() {std::cout << "Value is " << myval << std::endl;}
};void addone(Foo& foo) {foo.myval++;std::cout << "add 1" << std::endl;
}int main() {// Constructed a std::unique_ptrauto ptr1 = std::make_unique<Foo>(1);if (ptr1 != nullptr) ptr1->printval();{auto ptr2 = std::move(ptr1);	// move unique_ptr to ptr2addone(*ptr2);if (ptr2 != nullptr) ptr2->printval();if (ptr1 != nullptr) ptr1->printval();else std::cout << "ptr1 is destoryed" << std::endl;ptr1 = std::move(ptr2);		// move unique_ptr to ptr1if (ptr2 != nullptr) ptr2->printval();else std::cout << "ptr2 is destoryed" << std::endl;}return 0;
} // The unique_ptr will be destructed here

Output:

Foo::Foo
Value is 1
add 1
Value is 2
ptr1 is destoryed
ptr2 is destoryed
Foo::~Foo

2.3 std::weak_ptr

按理来说,使用shared_ptrunique_ptr已经能够满足大多数场景的需求了,为什么还需要一个weak_ptr呢,这是因为,shared_ptr当存在交叉引用的时候,仍然会导致内存泄漏的问题,举个例子:

#include <iostream>
#include <memory>
class A;
class B;class A {
public:std::shared_ptr<B> pointer;A() {std::cout << "Construct A" << std::endl;}~A() {std::cout << "Destory A" << std::endl;}
};class B {
public:std::shared_ptr<A> pointer;B() {std::cout << "Construct B" << std::endl;}~B() {std::cout << "Destory B" << std::endl;}
};int main() {auto a = std::make_shared<A>();auto b = std::make_shared<B>();a->pointer = b;b->pointer = a;return 0;
}

Output:

Construct A
Construct B

可以看到A和B并没有析构,说明这两块内存还没有得到释放,这是由于我们存在交叉引用,下面这张图很好的说明了这一点

Image

这是因为a,b内部的pointer同时又引用了a,b,这使得a,b的引用计数变为2了,离开作用域的时候,a,b的智能指针被析构,只能让这块区域的引用计数-1,这样就导致了a,b的引用计数不为零,造成了内存泄漏。

解决这个问题的好方式是使用std::weak_ptrstd::weak_ptr是一种弱引用,这种弱引用不会引起引用计数的增加,当换作弱引用的时候,最终的释放流程如图所示

Image
#include <iostream>
#include <memory>
class A;
class B;class A {
public:std::weak_ptr<B> pointer;A() {std::cout << "Construct A" << std::endl;}~A() {std::cout << "Destory A" << std::endl;}
};class B {
public:std::weak_ptr<A> pointer;B() {std::cout << "Construct B" << std::endl;}~B() {std::cout << "Destory B" << std::endl;}
};int main() {auto a = std::make_shared<A>();auto b = std::make_shared<B>();a->pointer = b;b->pointer = a;return 0;
}

Output:

Construct A
Construct B
Destory B
Destory A

需要注意的是std::weak_ptr只提供对一个或多个 shared_ptr 实例拥有的对象的访问,但不参与引用计数。 如果你想要观察某个对象但不需要其保持活动状态,请使用该实例,也就是说weak_ptr不能使用->*来访问实例对象的方法。

Reference

[1]智能指针(现代 C++)

[2]现代C++教程:高速上手C++ 11/14/17/20

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/diannao/2439.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

Java 网络编程之TCP(三):基于NIO实现服务端,BIO实现客户端

前面的文章&#xff0c;我们讲述了BIO的概念&#xff0c;以及编程模型&#xff0c;由于BIO中服务器端的一些阻塞的点&#xff0c;导致服务端对于每一个客户端连接&#xff0c;都要开辟一个线程来处理&#xff0c;导致资源浪费&#xff0c;效率低。 为此&#xff0c;Linux 内核…

华为数通HCIA ——企业网络架构以及产品线

一.学习目标&#xff1a;精讲网络技术&#xff0c;可以独立搭建和维护中小企业网络&#xff01; 模拟器&#xff08;华为方向请安装ENSP&#xff0c;Ensp-Lite已有安装包&#xff0c;号称功能更加完善-这意味着要耗费更多的系统资源但是仅对华为内部伙伴申请后方可使用&#x…

VS2022配置和搭建QT

一、下载QT 可以去QT官网下载:https://www.qt.io/product/development-tools。 直接安装。 二、安装qt插件 直接在vs插件市场搜索就行。 安装的时候根据提示&#xff0c;关闭vs自动安装 再次进去vs提示你选择qt版本&#xff0c;psth里边找到安装版本的qmake.exe就行 配…

卡尔曼滤波器(一):卡尔曼滤波器简介

观看MATLAB技术讲座笔记&#xff0c;该技术讲座视频来自bilibili账号&#xff1a;MATLAB中国。 一、什么是卡尔曼滤波器 卡尔曼滤波器是一种优化估计算法&#xff0c;是一种设计最优状态观测器的方法&#xff0c;其功能为&#xff1a; 估算只能被间接测量的变量&#xff1b;通…

https加密证书

网站要出去安全模式访问&#xff0c;加强网络安全就需要使用HTTPS加密证书。 本文主要介绍什么是HTTPS加密证书&#xff0c;如何申请HTTPS加密证书&#xff0c;如何安装HTTPS加密证书等问题展开讨论。 什么是HTTPS加密证书&#xff1f; HTTPS加密证书的行业产品用语叫作SSL证…

互联网大佬座位排排坐:马化腾第一,雷军第二

关注卢松松&#xff0c;会经常给你分享一些我的经验和观点。 这是马化腾、雷军、张朝阳、周鸿祎的座位&#xff0c;我觉得是按照互联网地位排序的。 马化腾坐头把交椅&#xff0c;这个没毛病&#xff0c;有他在的地方&#xff0c;其他几位都得喊声“大哥”。雷军坐第二把交椅…

缓解工作压力的小窍门:保持健康与创新

目录 1 前言2 工作与休息的平衡3 保持心理健康4 社交与网络建设5 结语 1 前言 作为程序员&#xff0c;我们常常承受着高度的工作压力和持续的创新挑战。为了保持高效和健康&#xff0c;我们需要采取一些方法来缓解工作压力&#xff0c;同时促进个人的心理和身体健康。 2 工作…

如何在PostgreSQL中设置自动清理过期数据的策略

文章目录 方法一&#xff1a;使用临时表和定期清理步骤&#xff1a;示例代码&#xff1a;创建临时表&#xff1a;定期清理脚本&#xff08;bash psql&#xff09;&#xff1a; 方法二&#xff1a;使用分区表和定期清理步骤&#xff1a;示例代码&#xff1a;创建分区表&#xf…

初始化Git仓库时应该运行哪个命令?

文章目录 初始化Git仓库时&#xff0c;你应该运行git init这个命令。这个命令的作用是在你当前所在的目录里创建一个新的Git仓库。这样&#xff0c;你就可以在这个目录里开始使用Git来管理你的文件了。 下面我给你举个详细的例子来说明一下&#xff1a; 首先&#xff0c;你需要…

【Mysql】用frm和ibd文件恢复mysql表数据

问题 总是遇到mysql服务意外断开之后导致mysql服务无法正常运行的情况&#xff0c;使用Navicat工具查看能够看到里面的库和表&#xff0c;但是无法获取数据记录&#xff0c;提示数据表不存在。 这里记录一下用frm文件和ibd文件手动恢复数据表的过程。 思路 1、frm文件&…

【代码】Python3|用Python PIL压缩图片至指定大小,并且不自动旋转

代码主体是GPT帮我写的&#xff0c;我觉得这个功能非常实用。 解决自动旋转问题参考&#xff1a;一行代码解决PIL/OpenCV读取图片出现自动旋转的问题&#xff0c;增加一行代码image ImageOps.exif_transpose(image) 即可恢复正常角度。 from PIL import Image, ImageOpsdef …

Linux:Win10平台上,用VMware安装Centos7.x及系统初始化关键的相关配置(分步骤操作,详细,一篇足以)

VMware安装Centos7.x镜像的详细步骤&#xff1a;VMWare安装Centos系统&#xff08;无桌面模式&#xff09; 我这里是为了安装Hadoop集群&#xff0c;所以&#xff0c;以下这些步骤是必须进行的 如果你是学习Linux&#xff0c;可以跳过非必须的那些配置项 我安装的版本是&…

集群工具之HAProxy

集群工具之HAProxy HAProxy简介 它是一款实现负载均衡的调度器适用于负载特别大的web站点HAProxy的工作模式 mode http&#xff1a;只适用于web服务mode tcp&#xff1a;适用于各种服务mode health&#xff1a;仅做健康检查&#xff0c;很少使用 配置HAProxy client&#x…

基于JAVA的机场航班起降与协调管理系统

毕业设计&#xff08;论文&#xff09;任务书 第1页 毕业设计&#xff08;论文&#xff09;题目&#xff1a; 基于JAVA的机场航班起降与协调管理系统 毕业设计&#xff08;论文&#xff09;要求及原始数据&#xff08;资料&#xff09;&#xff1a; 1&#xff0e;综述机场航班调…

【java配置】jpcap的下载与idea配置

解决报错&#xff1a;Cannot resolve symbol ‘jpcap’ 1. jpcap的下载 官网下载链接 百度网盘下载 双击WinpPca安装&#xff0c;jacap1和jpcap2任选其中之一 2. idea配置 &#xff08;1&#xff09;查看当前使用jdk目录 File -> Project Settings -> SDKs &#…

【1577】java网吧收费管理系统Myeclipse开发mysql数据库web结构java编程计算机网页项目

一、源码特点 java 网吧收费管理系统是一套完善的java web信息管理系统&#xff0c;对理解JSP java编程开发语言有帮助&#xff0c;系统具有完整的源代码和数据库&#xff0c;系统主要采用B/S模式开发。开发环境为 TOMCAT7.0,Myeclipse8.5开发&#xff0c;数据库为Mysql5.0…

项目实践---贪吃蛇小游戏(下)

对于贪吃蛇小游戏&#xff0c;最主要的还是主函数部分&#xff0c;这里就和大家一一列举出来&#xff0c;上一章已经写过头文件了&#xff0c;这里就不多介绍了。 首先就是打印桌面&#xff0c;也就是背景&#xff0c;则对应的代码为&#xff1a; void SetPos(short x, short …

MLLM | Mini-Gemini: 挖掘多模态视觉语言大模型的潜力

香港中文、SmartMore 论文标题&#xff1a;Mini-Gemini: Mining the Potential of Multi-modality Vision Language Models Code and models are available at https://github.com/dvlab-research/MiniGemini 一、问题提出 通过更高分辨率的图像增加视觉标记的数量可以丰富…

Power BI 如何创建页面导航器?(添加目录按钮/切换页面按钮)

Power BI 中页导航是什么&#xff1f; 在Power BI中&#xff0c;页导航&#xff08;Page Navigation&#xff09;是指在报告中创建多个页面&#xff08;页&#xff09;&#xff0c;然后允许用户在这些页面之间进行导航的功能。 如下图所示&#xff0c;页导航的选项和报告中的…

嵌入式学习59-ARM8(中断,ADC,内核定时器和传感器)

什么是中断顶半部和底半部 &#xff1f; &#xff08;部分记忆&#xff09;背 上半部&#xff1a; …