当前位置: 首页 > news >正文

C++异常与智能指针,资源泄露

一.异常的抛出和捕获

  1. 抛出:通过抛出(throw)⼀个对象来引发⼀个异常(throw执行时,throw后面的语句将不再被执行)
  2. 捕获:用catch来捕获(catch可能是同⼀函数中的⼀个局部的catch,也可能是调用链中另⼀个函数中的catch,控制权从throw位置转移到了catch位置)

抛出异常对象后,会生成⼀个异常对象的拷贝,因为抛出的异常对象可能是⼀个局部对象,所以会 生成⼀个拷贝对象,这个拷贝的对象会在catch子句后销毁。(这里的处理类似于函数的传值返 回)

//基本结构
try {// 可能抛出异常的代码if (错误条件) {throw 异常值; // 抛出异常}
} catch (异常类型 变量名) {// 处理异常的代码
}

简单除法异常示例

#include <iostream>
using namespace std;// 除法函数,当除数为0时抛出异常
double divide(double a, double b) {if (b == 0) {// 抛出字符串类型的异常throw "除数不能为0";}return a / b;
}int main() {double x = 10, y = 0, result;try {result = divide(x, y);cout << "结果: " << result << endl; // 如果抛出异常,这行不会执行} catch (const char* errorMsg) { // 捕获字符串类型的异常cout << "错误: " << errorMsg << endl;}cout << "程序继续执行..." << endl;return 0;
}

在抛出异常之后,程序暂停当前函数的执行,开始寻找与之匹配的catch子句,首先检查throw本⾝是否在try块内部,如果在则查找匹配的catch语句,如果有匹配的,则跳到catch的地方进行处理。如果当前函数中没有try/catch子句,或者有try/catch子句但是类型不匹配,则退出当前函数,继续 在外层调用函数链中查找,上述查找的catch过程被称为栈展开 。

 栈展开简单示例

#include <iostream>
using namespace std;void func3() {cout << "在func3中抛出异常" << endl;throw "发生错误";
}void func2() {cout << "调用func3" << endl;func3(); // 调用可能抛出异常的函数cout << "func3调用后(不会执行)" << endl;
}void func1() {cout << "调用func2" << endl;func2(); // 调用可能抛出异常的函数cout << "func2调用后(不会执行)" << endl;
}int main() {try {cout << "调用func1" << endl;func1();} catch (const char* msg) {cout << "在main中捕获异常: " << msg << endl;}return 0;
}
//输出结果
//调用func1
//调用func2
//调用func3
//在func3中抛出异常
//在main中捕获异常: 发生错误

1.1异常类型

C++ 可以抛出任何类型的异常,包括:

  • 基本数据类型(int, double 等)
  • 字符串
  • 自定义类 / 结构体

自定义异常类:

#include <iostream>
#include <string>
using namespace std;// 自定义异常类
class DivideByZeroException {
private:string message;
public:DivideByZeroException(string msg) : message(msg) {}// 获取错误信息string getMessage() const {return message;}
};double divide(double a, double b) {if (b == 0) {// 抛出自定义异常throw DivideByZeroException("除数不能为0");}return a / b;
}int main() {try {cout << divide(10, 2) << endl;  // 正常执行cout << divide(10, 0) << endl;  // 抛出异常} catch (const DivideByZeroException& e) {  // 捕获自定义异常cout << "捕获到异常: " << e.getMessage() << endl;}return 0;
}

二.资源泄露

2.1 RAII:资源获取即初始化

RAII(Resource Acquisition Is Initialization)的核心思想是:将资源的生命周期与对象的生命周期绑定。具体来说:

  1. 资源在对象的构造函数中获取(申请);
  2. 资源在对象的析构函数中释放(归还);
  3. 当对象超出作用域时,编译器会自动调用析构函数,从而确保资源被释放。

在使用手动管理文件资源很容易出现忘记关闭文件而导致文件泄露。

出现这种情况可以使用RAII的思想

// RAII方式:用对象管理文件资源(安全)
#include <fstream>
#include <stdexcept>
using namespace std;// 定义一个RAII类,绑定文件资源的生命周期
class FileHandler {
private:ofstream file; // 资源(文件句柄)作为对象的成员
public:// 构造函数:获取资源(打开文件)FileHandler(const string& filename) {file.open(filename);if (!file.is_open()) {throw runtime_error("文件打开失败"); // 打开失败则抛异常}}// 析构函数:释放资源(关闭文件)~FileHandler() {if (file.is_open()) {file.close(); // 无论如何,对象销毁时一定会关闭文件}}// 提供操作文件的接口ofstream& get_file() {return file;}
};void write_to_file() {// 1. 创建对象时,自动获取资源(调用构造函数打开文件)FileHandler handler("data.txt"); // 2. 使用资源handler.get_file() << "hello RAII"; // 3. 函数结束时,handler对象超出作用域,自动调用析构函数释放资源(关闭文件)// 即使中间有return或异常,析构函数仍会被调用
}int main() {try {write_to_file();} catch (const exception& e) {// 处理异常}return 0;
}

2.2. 智能指针:RAII 在内存管理中的应用 

智能指针是 C++ 标准库提供的模板类,其本质是用 RAII 思想管理动态内存的对象:

  1. 智能指针在构造时获取内存(接收new的返回值);
  2. 在析构时自动释放内存(调用delete);
  3. 行为类似指针(可通过*和->访问所指对象

2.2.1 auto_ptr: 

拷贝时把被拷贝对象的资源的管理权转移给拷贝对象,导致被拷贝对象悬空。

2.2.2unique_ptr: 

unique_ptr表示对内存的独占所有权(同一时间只有一个unique_ptr指向该内存),适用于资源只能被一个对象使用的场景。(不支持拷贝,只支持移动)

2.2.3  shared_ptr:

shared_ptr通过引用计数(析构多次)实现内存的共享所有权:多个shared_ptr可指向同一内存,当最后一个shared_ptr销毁时,才释放内存。

#include <iostream>
#include <memory>
using namespace std;int main() {// 创建shared_ptr,引用计数初始化为1shared_ptr<int> sptr1 = make_shared<int>(20); cout << "引用计数:" << sptr1.use_count() << endl; // 输出:1// 复制sptr1,引用计数变为2(共享所有权)shared_ptr<int> sptr2 = sptr1; cout << "引用计数:" << sptr1.use_count() << endl; // 输出:2// sptr2超出作用域,引用计数减为1{shared_ptr<int> sptr3 = sptr1;cout << "引用计数:" << sptr1.use_count() << endl; // 输出:3}cout << "引用计数:" << sptr1.use_count() << endl; // 输出:2// 最后sptr1和sptr2销毁,引用计数变为0,内存被释放return 0;
}
定制删除器 

shared_ptr默认的释放逻辑是调用delete,但以下场景需要自定义删除行为:

  1. 管理动态数组(需要用delete[]而不是delete)
  2. 释放非内存资源(如文件指针、网络套接字)
  3. 执行额外的清理操作(如日志记录、状态重置)

删除器可以是:函数指针 , 函数对象( functor ),Lambda 表达式(C++11 及以上)
当shared_ptr的引用计数变为 0 时,会自动调用定制的删除器来释放资源。 

#include <iostream>
#include <memory>
using namespace std;int main() {// 方式1:使用函数指针作为删除器auto array_deleter = [](int* ptr) {cout << "释放动态数组" << endl;delete[] ptr; // 注意使用delete[]};// 创建shared_ptr时指定删除器shared_ptr<int> arr_ptr(new int[5]{1,2,3,4,5}, array_deleter);// 使用数组(需注意shared_ptr不直接支持[]操作,需手动获取原始指针)for (int i = 0; i < 5; ++i) {cout << arr_ptr.get()[i] << " "; // get()获取原始指针}cout << endl;// 当arr_ptr销毁时,会自动调用array_deleter,用delete[]释放数组return 0;
}

定制删除器相关代码 

#include<iostream>
#include<assert.h>
#include<functional>
using namespace std;
namespace happy
{template<class T>class shared_ptr{public :shared_ptr(T*ptr=nullptr):_ptr(ptr),pcount(new int(1)){}shared_ptr(const shared_ptr<T>& sp):_ptr(sp._ptr),pcount(sp.pcount){(*pcount)++;}template<class D>shared_ptr(T*ptr,D* del):_ptr(ptr),pcount(new int (1)),_del(del){}void release(){if (--(*pcount) == 0){//定制删除器_del(_ptr);//delete _ptr;delete pcount;}}~shared_ptr(){release();}shared_ptr<T>& operator=(const shared_ptr<T>& sp){//处理自己给自己赋值情况if (_ptr != sp._ptr){release();_ptr = sp._ptr;pcount = sp.pcount;return *this;}}//像指针一样使用T& operator*(){return *_ptr;}T* operator->(){return &_ptr;}private:T* _ptr;int* pcount;function<void(T*)> _del = [](T* ptr) {delete ptr; };};
}
int main()
{happy::shared_ptr<int> sp1(new int(1));happy::shared_ptr<int> sp2(sp1);happy::shared_ptr<int> sp3(new int(2));sp1 = sp3;sp1 = sp1;sp1 = sp2;return 0;
}
make_shared: 

shared_ptr 提供了两种主要方式创建实例:一种是通过已有的资源指针构造,另一种是使用 make_shared 直接通过资源的初始化值来构造。

两种构造的对比
#include <memory>
using namespace std;int main() {// 先手动用new创建对象,再传给shared_ptrshared_ptr<int> ptr(new int(42));// 直接传入初始化值,make_shared内部会自动分配内存并初始化shared_ptr<int> ptr = make_shared<int>(42);return 0;
}
make_shared的优势 

1:更高的效率
make_shared 会一次性分配内存(同时存储对象和 shared_ptr 的控制块),而 new + shared_ptr 构造需要两次内存分配(一次给对象,一次给控制块)。
2:更安全(避免内存泄漏风险)
考虑以下场景,make_shared 能避免潜在的内存泄漏:

#include <memory>
#include <iostream>
using namespace std;void process(shared_ptr<int> ptr, int value) {// 处理逻辑
}int main() {// 危险:可能导致内存泄漏process(shared_ptr<int>(new int(42)), some_function()); // 原因:C++允许先执行new int(42),再调用some_function()// 如果some_function()抛出异常,shared_ptr还未构造,new分配的内存会泄漏// 安全:make_shared能避免这种情况process(make_shared<int>(42), some_function());// 因为make_shared是一个函数调用,要么完全成功(内存分配+构造),要么完全失败(不分配内存)return 0;
}
shared_ptr循环引用问题 

循环引用指的是两个或多个shared_ptr互相持有对方的引用,形成一个闭环,使得引用计数始终无法归零,从而资源无法释放。

例子:

#include <iostream>
#include <memory>
using namespace std;class Child; // 前向声明class Parent {
public:// 父对象持有子对象的shared_ptrshared_ptr<Child> child_ptr;Parent() { cout << "Parent构造" << endl; }~Parent() { cout << "Parent析构" << endl; } // 析构函数不会被调用
};class Child {
public:// 子对象持有父对象的shared_ptrshared_ptr<Parent> parent_ptr;Child() { cout << "Child构造" << endl; }~Child() { cout << "Child析构" << endl; } // 析构函数不会被调用
};int main() {// 创建父对象和子对象shared_ptr<Parent> parent = make_shared<Parent>();shared_ptr<Child> child = make_shared<Child>();// 互相引用:形成循环parent->child_ptr = child;  // parent的引用计数仍为1,child的引用计数变为2child->parent_ptr = parent; // child的引用计数仍为2,parent的引用计数变为2// 函数结束时,parent和child的引用计数各减1(变为1)// 但由于互相持有,引用计数始终不为0,析构函数不会被调用return 0;
}

 解决方法:使用weak_ptr

weak_ptr是一种 "弱引用" 智能指针,它持有对象的引用但不增加引用计数,可以用来观察对象但不影响其生命周期。用weak_ptr替代循环引用中的一方的shared_ptr,即可打破循环。

2.2.4 weak_ptr :

weak_ptr的产生本质是要解决shared_ptr 的⼀个循环引用导致内存泄漏的问题

#include <iostream>
#include <memory>
using namespace std;class Child;class Parent {
public:shared_ptr<Child> child_ptr; // 父对象仍用shared_ptr持有子对象Parent() { cout << "Parent构造" << endl; }~Parent() { cout << "Parent析构" << endl; }
};class Child {
public:weak_ptr<Parent> parent_ptr; // 子对象用weak_ptr持有父对象(关键修改)Child() { cout << "Child构造" << endl; }~Child() { cout << "Child析构" << endl; }
};int main() {shared_ptr<Parent> parent = make_shared<Parent>();shared_ptr<Child> child = make_shared<Child>();parent->child_ptr = child;  // child引用计数变为2child->parent_ptr = parent; // parent引用计数仍为1(weak_ptr不增加计数)// 函数结束时:// 1. child的引用计数减1(变为1)// 2. parent的引用计数减1(变为0,Parent对象被销毁)// 3. Parent销毁后,其child_ptr被释放,child的引用计数减1(变为0,Child对象被销毁)return 0;
}

weak_ptr不能直接访问对象,需先通过lock()方法转换为shared_ptr(确保对象未被销毁):

// 在Child类中访问Parent对象
void Child::access_parent() {// lock()返回shared_ptr:若对象存在则非空,否则为空shared_ptr<Parent> temp = parent_ptr.lock();if (temp) {// 安全访问父对象} else {// 父对象已被销毁}
}

三.资源泄露 

内存泄漏指因为疏忽或错误造成程序未能释放已经不再使用的内存,⼀般是忘记释放或者发生异常释放程序未能执行导致的。内存泄漏并不是指内存在物理上的消失,而是应用程序分配某段内存后,因为设计错误,失去了对该段内存的控制,因而造成了内存的浪费。

 

 

 

http://www.dtcms.com/a/313556.html

相关文章:

  • CMake 命令行参数完全指南
  • 【动态规划算法】路径问题
  • kubernetes基础知识
  • Linux命令基础(下)
  • Day22--回溯--77. 组合,216. 组合总和 III,17. 电话号码的字母组合
  • 深入剖析Java拦截器:从原理到实战
  • Python3 中使用zipfile进行文件(夹)的压缩、解压缩
  • 一加Ace5无法连接ColorOS助手解决(安卓设备ADB模式无法连接)
  • 跟我学C++中级篇——常函数
  • javaweb开发之Servlet笔记
  • vulhub ELECTRICAL靶场攻略
  • 【Reading Notes】(8.4)Favorite Articles from 2025 April
  • Back to the Features:附录B
  • 控制建模matlab练习08:根轨迹
  • 常⻅框架漏洞
  • 电力电子技术知识总结-----PWM知识点
  • 基于Spring Data JPA与Redis二级缓存集成实战指南
  • C语言基础12——结构体2
  • vulhub-ELECTRICAL靶机
  • Python Pandas.factorize函数解析与实战教程
  • 验房收房怎么避免被坑?
  • elk快速部署、集成、调优
  • [CISCN 2023 初赛]go_session
  • 第十章:如何真正使用Java操作redis
  • VUE-第二季-01
  • Day 30:模块和库的导入
  • Git 常用命令指南:从入门到高效开发
  • 数据结构之链表
  • sublime text2配置
  • 设备维护计划制定指南:基于数据驱动的全流程技术实现