【C++进阶】--智能指针

1. 为什么需要智能指针

首先我们来分析一下下面这段代码

#include<iostream>
using namespace std;
int div()
{int a, b;cin >> a >> b;if (b == 0)throw invalid_argument("除0错误");return a / b;
}
void Func()
{int* p1 = new int;int* p2 = new int;cout << div() << endl;delete p1;delete p2;
}
int main()
{try{Func();}catch (exception& e){cout << e.what() << endl;}return 0;
}

通过分析我们可以知道会有下面三种情况的异常
1、p1这里new 抛异常,由于不存在释放的问题,不需要处理。
2、p2这里new 抛异常,p1成功申请空间,只需抛出异常,然后释放p1。
3、div调用这里又会抛异常,p1、p2都成功申请空间,只需抛出异常,然后释放p1、p2。

然后对代码进行改进,改进代码如下:

#include<iostream>
using namespace std;int div()
{int a, b;cin >> a >> b;if (b == 0)throw invalid_argument("除零错误");return a/b;
}
void Func()
{int* p1 = new int;int* p2 = nullptr;try{p2 = new int;}catch (...){delete p1;throw;}try{cout << div() << endl;}catch (...){delete p1;delete p2;throw;}delete p1;delete p2;
}
int main()
{try{Func();}catch (exception& e){cout << e.what() << endl;}return 0;
}

可以看到代码可读性不高,并且很繁琐,所以我们有没有什么方法改进呢?

2. 内存泄漏

2.1 什么是内存泄漏,内存泄漏的危害

**什么是内存泄漏:**内存泄漏是指因为疏忽或错误造成程序未能释放已经不再使用的内存的情况。内存泄漏并不是指物理上的消失,而是应用程序分配某段内存后,因为设计错误,失去了对该段内存的控制,因而造成了内存的浪费

内存泄漏的危害:长期运行的程序出现内存泄漏,影响很大,如操作系统、后台服务等,出现内存泄漏会导致响应越来越慢,最终卡死

2.2 内存泄漏分类

  • 堆内存泄漏(heap leak)
    堆内存指的是程序执行中宜居需要分配通过malloc/calloc/realloc/new等从堆中分配的一块内存,用完后必须通过调用相应的free或者delete删掉。假设程序的设计错误导致这部分内存没有被释放,那么以后这部分空间将无法再被使用,就会产生heap leak
  • 系统资源泄漏
    指程序使用系统分配的资源,比方套接字、文件描述符、管道等没有使用对应的函数释放掉,导致系统资源的浪费,严重可导致系统效能减少,系统执行不稳定

2.3 如何避免内存泄漏

  1. 工程前期良好的设计规范,养成良好的编码规范,申请的内存空间记着匹配的去释放。ps:这个理想状态。但是如果碰上异常时,就算注意释放了,还是可能会出问题。需要下一条智能指针来管理才有保证。
  2. 采用RAII思想或者智能指针来管理资源。
  3. 有些公司内部规范使用内部实现的私有内存管理库。这套库自带内存泄漏检测的功能选项。
  4. 出问题了使用内存泄漏工具检测。ps:不过很多工具都不够靠谱,或者收费昂贵。

总结: 内存泄漏非常常见,解决方案分为两种:1、事前预防型。如智能指针等。2、事后查错型。如泄漏检测工具

3.智能指针的使用和原理

3.1 RAII

RAII(Resource Acquisition Is Initialization)是一种利用对象生命周期来控制程序资源(如内存问题、文件句柄、网络连接、互斥量等)的简单技术
在对象构造时获取资源, 接着控制对资源的访问使之在对象的生命周期内始终保持有效,最后在对象析构的时候释放资源。借此,我们实际上把管理一份资源的责任托管给了一个对象。

这种做法有两大好处:

  • 不需要显式的释放资源
  • 采用这种方式,对象所需的资源在其声明周期内始终保持有效
#include<iostream>
using namespace std;template<class T>
class SmartPtr
{
public:SmartPtr(T* ptr):_ptr(ptr){}~SmartPtr(){cout << "delete:" << &_ptr << endl;delete _ptr;}
private:T* _ptr;
};
int div()
{int a, b;cin >> a >> b;if (b == 0)throw invalid_argument("除零错误");return a/b;
}
void Func()
{SmartPtr<int> sp1(new int);SmartPtr<int> sp2(new int);cout << div() << endl;
}
int main()
{try{Func();}catch (exception& e){cout << e.what() << endl;}return 0;
}

运行结果:

在这里插入图片描述

3.2 智能指针的原理

上述的SmartPtr还不能将其称为智能指针,因为他还不具有指针的行为。指针可以解引用,也可以通过->去访问所指空间中的内容,因此:AutoPtr模板类中还得需要将* 、->重载下,才可让其像指针一样去使用

#include<iostream>
using namespace std;template<class T>
class SmartPtr
{
public:SmartPtr(T* ptr):_ptr(ptr){}~SmartPtr(){cout << "delete:" << &_ptr << endl;delete _ptr;}T& operator*(){return *_ptr;}T& operator->(){return _ptr;}
private:T* _ptr;
};
int div()
{int a, b;cin >> a >> b;if (b == 0)throw invalid_argument("除零错误");return a/b;
}
void Func()
{SmartPtr<int> sp1(new int);SmartPtr<int> sp2(new int);cout << div() << endl;
}
int main()
{try{Func();}catch (exception& e){cout << e.what() << endl;}return 0;
}

总结一下智能指针的原理:

  1. RAII特性
  2. 重载operator*和operator->,具有像指针一样的行为

3.3 std::auto_ptr

C++98版本的库中就提供了auto_ptr的智能指针。
auto_ptr的实现原理:管理权转移的思想

#pragma once
#include<iostream>
using namespace std;
namespace Maria
{template<class T>class auto_ptr{public:auto_ptr(T* ptr):_ptr(ptr){}~auto_ptr(){if (_ptr){cout << "delete:" << &_ptr << endl;delete _ptr;}}//管理权转移auto_ptr(auto_ptr<T>& ap):_ptr(ap._ptr){ap._ptr = nullptr;}T& operator*(){return *_ptr;}T* operator->(){return _ptr;}private:T* _ptr;};void test_auto(){auto_ptr<int> ap1(new int(1));auto_ptr<int> ap2(ap1);}
}

运行结果:
在这里插入图片描述
但是当我们想对被ap2拷贝的ap1进行解引用的时候,我们就发现程序崩了。
在这里插入图片描述
也就是说,ap1悬空了,访问不到了。

3.4 std::unique_ptr

实现原理:简单粗暴的防拷贝

#pragma once
#include<iostream>
using namespace std;
namespace Maria
{template<class T>class unique_ptr{public:unique_ptr(T* ptr):_ptr(ptr){}~unique_ptr(){if (_ptr){cout << "delete:" << &_ptr << endl;delete _ptr;}}T& operator*(){return *_ptr;}T* operator->(){return _ptr;}//防拷贝//拷贝构造和赋值是默认成员函数,不写会自动生成//unique_ptr(const unique_ptr<T>& up) = delete;//C++11private:T* _ptr;unique_ptr(const unique_ptr<T>& up);//C++98};void test_unique(){unique_ptr<int> up1(new int(1));unique_ptr<int> up2(up1);}
}T* operator->(){return _ptr;}//防拷贝//拷贝构造和赋值是默认成员函数,不写会自动生成//unique_ptr(const unique_ptr<T>& up) = delete;//C++11private:T* _ptr;unique_ptr(const unique_ptr<T>& up);//C++98};void test_unique(){unique_ptr<int> ap1(new int(1));unique_ptr<int> ap2(ap1);}
}

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

可以看到当我们想要拷贝up1的时候,就无法调用拷贝构造了

3.5 std::shared_ptr

实现原理:通过引用计数的方式来实现多个shared_ptr对象之间共享资源。

  1. shared_ptr在其内部,给每个资源都维护了一份计数,用来记录该份资源被几个对象共享
  2. 在对象被销毁的时候(也就是析构函数调用),就说明自己不使用该资源了,对象的引用计数减一
  3. 如果引用计数是0,就说明自己是最后一个使用该资源的对象,必须释放该资源
  4. 如果不是0,就说明除了自己还有其他对象在使用该份资源,不能释放该资源,否则其他对象就成野指针了

#pragma once
#include<iostream>
#include<mutex>
using namespace std;
#include<thread>
namespace Maria
{template<class T>class shared_ptr{public:shared_ptr(T* ptr):_ptr(ptr),_pcount(new int(1)),_pmtx(new mutex){}~shared_ptr(){Release();}void Release(){bool deleteFlag = false;_pmtx->lock();if (--(*_pcount) == 0){cout << "delete:" << &_ptr << endl;delete _ptr;delete _pcount;deleteFlag = true;}_pmtx->unlock();if (deleteFlag){delete _pmtx;}}T& operator*(){return *_ptr;}T* operator->(){return _ptr;}//sp2 = sp4shared_ptr<T> operator=(const shared_ptr<T>& sp){//没有管理同一块资源if (_ptr!= sp._ptr){Release();_ptr = sp._ptr;_pcount = sp._pcount;_pmtx = sp._pmtx;AddCount();}return *this;}void AddCount(){_pmtx->lock();++(*_pcount);_pmtx->unlock();}T* get(){return _ptr;}int use_count(){return *_pcount;}shared_ptr(const shared_ptr<T>& sp):_ptr(sp._ptr), _pcount(sp._pcount), _pmtx(sp._pmtx){AddCount();}private:T* _ptr;int* _pcount;mutex* _pmtx;};struct Date{int _year = 0;int _month = 0;int _day = 0;};void sharePtrFunc(Maria::shared_ptr<Date>& sp, size_t n, mutex& mtx){cout << sp.get() << endl;for (size_t i = 0; i < n;i++){Maria::shared_ptr<Date> copy(sp);mtx.lock();sp->_year++;sp->_month++;sp->_day++;mtx.unlock();}}void test_shared(){shared_ptr<int> sp1(new int(1));shared_ptr<int> sp2(sp1);shared_ptr<int> sp3(sp2);shared_ptr<int> sp4(new int(10));sp4 = sp1;sp1 = sp1;sp1 = sp2;}void test_shared_safe(){Maria::shared_ptr<Date> p(new Date);const size_t n = 1000000;mutex mtx;thread t1(sharePtrFunc, ref(p), n, ref(mtx));thread t2(sharePtrFunc, ref(p), n, ref(mtx));t1.join();t2.join();cout << p.use_count() << endl;cout << p->_year << endl;cout << p->_month << endl;cout << p->_day << endl;}
}

运行结果:
在这里插入图片描述
循环引用分析

  1. n1和n2两个指针对象指向两个节点,引用计数变成1,我们不需要手动delete
  2. n1的_next指向n2,n2的_prev指向n1,引用计数变成2
  3. n1和n2析构,引用计数减到1,但是_next还指向下一个节点。但是_prev还指向上一个节点。
  4. 也就是说_next析构了,n2就释放了;_prev析构了,n1就释放了
  5. 但是_next属于node的成员,n1释放了,_next才会析构,而n1由_prev管理,_prev属于n2成员,所以这就叫循环引用,谁也不会释放
    对应下图情况一

解决方案:在引用计数的场景下,把节点中的_prev和_next改成weak_ptr就可以了
原理:node1->_next = node2;和node2->_prev = node1;时weak_ptr的_next和_prev不会增加node1和node2的引用计数

在这里插入图片描述

struct ListNode{std::weak_ptr<ListNode> _next;std::weak_ptr<ListNode> _prev;;int val;~ListNode(){cout << "~ListNode()" << endl;}};void test_shared_cycle(){std::shared_ptr<ListNode> n1 ( new ListNode);std::shared_ptr<ListNode> n2 (new ListNode);n1->_next = n2;n2->_prev = n1;}

运行结果:
在这里插入图片描述
继续分析上面的代码,我们可以发现释放对象我们都是写死使用delete,那么对象如果不是new出来的,我们又应该怎样释放呢?shared_ptr设计了一个删除器来解决这个问题

#pragma once
#include<functional>
#include<iostream>
#include<mutex>
#include<thread>using namespace std;
namespace Maria
{template<class T>class shared_ptr{public:shared_ptr(T* ptr = nullptr):_ptr(ptr) , _pcount(new int(1)), _pmtx(new mutex){}template <class D>shared_ptr(T* ptr ,D del):_ptr(ptr), _pcount(new int(1)), _pmtx(new mutex),_del(del){}shared_ptr(const shared_ptr<T>& sp):_ptr(sp._ptr), _pcount(sp._pcount), _pmtx(sp._pmtx){AddCount();}~shared_ptr(){Release();}void Release(){bool deleteFlag = false;_pmtx->lock();if (--(*_pcount) == 0){if (_ptr){cout << "delete:" << &_ptr << endl;//delete _ptr;_del(_ptr);}delete _pcount;deleteFlag = true;}_pmtx->unlock();if (deleteFlag){delete _pmtx;}}T& operator*(){return *_ptr;}T* operator->(){return _ptr;}//sp2 = sp4shared_ptr<T> operator=(const shared_ptr<T>& sp){//没有管理同一块资源if (_ptr != sp._ptr){Release();_ptr = sp._ptr;_pcount = sp._pcount;_pmtx = sp._pmtx;AddCount();}return *this;}void AddCount(){_pmtx->lock();++(*_pcount);_pmtx->unlock();}T* get()const{return _ptr;}int use_count(){return *_pcount;}private:T* _ptr;int* _pcount;mutex* _pmtx;function<void(T*)> _del = [](T* ptr) {/*delete ptr; cout << "delete ptr" << endl;*/ };};struct Date{int _year = 0;int _month = 0;int _day = 0;~Date() {}};void sharePtrFunc(Maria::shared_ptr<Date>& sp, size_t n, mutex& mtx){cout << sp.get() << endl;for (size_t i = 0; i < n; i++){Maria::shared_ptr<Date> copy(sp);mtx.lock();sp->_year++;sp->_month++;sp->_day++;mtx.unlock();}}void test_shared(){shared_ptr<int> sp1(new int(1));shared_ptr<int> sp2(sp1);shared_ptr<int> sp3(sp2);shared_ptr<int> sp4(new int(10));sp4 = sp1;sp1 = sp1;sp1 = sp2;}void test_shared_safe(){Maria::shared_ptr<Date> p(new Date);const size_t n = 1000000;mutex mtx;thread t1(sharePtrFunc, ref(p), n, ref(mtx));thread t2(sharePtrFunc, ref(p), n, ref(mtx));t1.join();t2.join();cout << p.use_count() << endl;cout << p->_year << endl;cout << p->_month << endl;cout << p->_day << endl;}template<class T>class weak_ptr{public:weak_ptr():_ptr(nullptr){}weak_ptr(const  shared_ptr<T>& sp):_ptr(sp.get()){}~weak_ptr(){cout << "~weak_ptr()" << endl;}T& operator*(){return *_ptr;}T* operator->(){return _ptr;}private:T* _ptr;};struct ListNode{Maria::weak_ptr<ListNode> _next;Maria::weak_ptr<ListNode> _prev;;int val;~ListNode(){cout << "~ListNode()" << endl;}};void test_shared_cycle(){Maria::shared_ptr<ListNode> n1 ( new ListNode);Maria::shared_ptr<ListNode> n2 (new ListNode);cout << n1.use_count() << endl;cout << n2.use_count() << endl;n1->_next = n2;n2->_prev = n1;cout << n1.use_count() << endl;cout << n2.use_count() << endl;}//定制删除器template<class T>struct DeleteArray{void operator()(T* ptr){cout << "void operator()(T* ptr)" << endl;delete[] ptr;}};void test_shared_delete(){Maria::shared_ptr<Date> spa0(new Date);Maria::shared_ptr<Date> spa1(new Date[10], DeleteArray<Date>());Maria::shared_ptr<Date> spa2(new Date[10], [](Date* ptr) {delete[] ptr;cout << "lambda delete[]" << endl; });Maria::shared_ptr<FILE> spa3(fopen("test.cpp", "r"), [](FILE* ptr) {fclose(ptr);cout << "lambda fclose" << endl; });}
}

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

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

相关文章

监控系统Prometheus--与第三方框架集成

文章目录 Prometheus和Flink集成拷贝jar包修改Flink配置为了运行测试程序&#xff0c;启动netcat启动hdfs、yarn&#xff0c;提交flink任务到yarn上可以通过8088跳到flinkUI的job页面&#xff0c;查看指标统计刷新Prometheus页面&#xff0c;如果有flink指标&#xff0c;集成成…

Matlab 2024安装教程(附免费安装包资源)

鼠标右击软件压缩包&#xff0c;选择“解压到MatlabR2024a“。 2.打开解压后的文件夹&#xff0c;鼠标右击“MATHWORKS_R2024A“选择装载。 鼠标右击“setup“选择”以管理员身份运行“。点击“是“&#xff0c;然后点击”下一步“。复制一下密钥粘贴至输入栏&#xff0c;然后…

【1000个GDB技巧之】GDB运行中如何动态更新内存的corefile?

场景 /proc/kcore包括了linux内存&#xff0c;但是在gdb试用中的时候&#xff0c;加载的可能支持某个快照。如何动态读取最新数据而不用退出重新加载&#xff0c;就使用GDB的core-file进行处理。 core-file /proc/kcore效果&#xff1a; 未更新前数据不会变化&#xff0c;更新…

【STL详解 —— stack和queue的介绍及使用】

STL详解 —— stack和queue的介绍及使用 stackstack的定义方式stack的使用 queuequeue的定义方式queue的使用 stack stack是一种容器适配器&#xff0c;专门用在具有后进先出操作的上下文环境中&#xff0c;其只能从容器的一端进行元素的插入与提取操作。 stack的定义方式 首…

鉴权设计(一)———— 登录验证

1、概述 网站系统出于安全性的考虑会对用户进行两个层面的校验&#xff1a;身份认证以及权限认证。这两个认证可以保证只有特定的用户才能访问特定的数据的需求。 本文先实现一个基于jwt拦截器redis注解实现的简单登录验证功能。 2、设计思路 jwt用于签发token。 拦截器用于拦…

Kubernetes的Ingress Controller

前言 Kubernetes暴露服务的方式有一下几种&#xff1a;LoadBlancer Service、ExternalName、NodePort Service、Ingress&#xff0c;使用四层负载均衡调度器Service时&#xff0c;当客户端访问kubernetes集群内部的应用时&#xff0c;数据包的走向如下面流程所示&#xff1a;C…

vue-router 原理【详解】hash模式 vs H5 history 模式

hash 模式 【推荐】 路由效果 在不刷新页面的前提下&#xff0c;根据 URL 中的 hash 值&#xff0c;渲染对应的页面 http://test.com/#/login 登录页http://test.com/#/index 首页 核心API – window.onhashchange 监听 hash 的变化&#xff0c;触发视图更新 window.onhas…

Kali系统开启SSH服务结合内网穿透工具实现无公网IP远程连接

文章目录 1. 启动kali ssh 服务2. kali 安装cpolar 内网穿透3. 配置kali ssh公网地址4. 远程连接5. 固定连接SSH公网地址6. SSH固定地址连接测试 本文主要介绍如何在Kali系统编辑SSH配置文件并结合cpolar内网穿透软件&#xff0c;实现公网环境ssh远程连接本地kali系统。 1. 启…

【群智能算法改进】一种改进的火鹰优化算法 改进的IFHO算法【Matlab代码#77】

文章目录 【获取资源请见文章第5节&#xff1a;资源获取】1. 原始火鹰优化算法1.1 种群初始化1.2 火鹰点火阶段1.3 猎物移动阶段 2. 改进的火鹰优化算法2.1 Tent映射种群初始化2.2 非线性复合自适应惯性权重随机抉择策略 3. 部分代码展示4. 仿真结果展示5. 资源获取 【获取资源…

【Python系列】pydantic版本问题

&#x1f49d;&#x1f49d;&#x1f49d;欢迎来到我的博客&#xff0c;很高兴能够在这里和您见面&#xff01;希望您在这里可以感受到一份轻松愉快的氛围&#xff0c;不仅可以获得有趣的内容和知识&#xff0c;也可以畅所欲言、分享您的想法和见解。 推荐:kwan 的首页,持续学…

机器学习 | 使用Scikit-Learn实现分层抽样

在本文中&#xff0c;我们将学习如何使用Scikit-Learn实现分层抽样。 什么是分层抽样&#xff1f; 分层抽样是一种抽样方法&#xff0c;首先将总体的单位按某种特征分为若干次级总体&#xff08;层&#xff09;&#xff0c;然后再从每一层内进行单纯随机抽样&#xff0c;组成…

1.9 数据结构之 并查集

编程总结 在刷题之前需要反复练习的编程技巧&#xff0c;尤其是手写各类数据结构实现&#xff0c;它们好比就是全真教的上乘武功 本栏目为学习笔记参考&#xff1a;https://leetcode.cn/leetbook/read/disjoint-set/oviefi/ 1.0 概述 并查集&#xff08;Union Find&#xff09…