effective c++ 介绍了C++中资源管理类(resource managing object / Resource acquisition is initialization RAII)。
- 获取资源后立刻放入对象
- 运用析构函数确保资源得到释放
- 谨慎复制(禁止拷贝,深拷贝,计数拷贝,转移所有权)
- 立即放入对象(指的是立即,所以最好独立成一个语句)
processWidget(std::shared_ptr<Widget><new Widget>, priority());
- 根据编译器实现的不同,上面的语句可能会在new Widget之后调用priority(),再将new出来的Widget放入RAII对象。若priority执行中抛了异常,那么这个资源就tm丢了。所以应该改成下面这样才安全
st::shared_ptr<Widget> pw(new Widget);
processWidget(pw, priority());
强调了异常安全性的概念。
- 不泄露任何资源(内存,锁,文件描述符,socket等连接)
- 不允许数据破坏(不会因为抛了异常而导致出现数据不一致)
异常安全函数需满足以下三个保证之一,按照这三个强度标准来实现函数以确保不会因为异常造成问题:
- 基本承诺 抛异常之后,程序类的任何事物仍然保持在有效状态下,抛异常之后,没有数据结构被破坏。
- 强烈保证 抛异常之后,程序回到执行这个函数之前的状态,即要么成功,要么不造成任何影响,像没发生过一样
- 不抛保证 保证不抛异常
下面是一个简单的demo,使用资源管理类来防止资源泄露。
#include <iostream>
#include <string>
using namespace std;
class Leak{ // 这是一个有意忘了在析构时释放资源的类,必然会造成100Byte的泄露
public:
Leak(){
cout << "Leak constructed." <<endl;
data = (char*) malloc(100);
}
~Leak(){
cout << "Leak destroyed." <<endl;
}
private:
char* data = nullptr;
};
class ExceptionSafe{ // 使用对象来管理资源,可以确保资源的释放 effcpp
public:
ExceptionSafe() {
cout << "ExceptionSafe constructed." <<endl;
data = (char*) malloc(10000);
}
~ExceptionSafe() {
cout << "ExceptionSafe destroyed." <<endl;
free(data);
}
private:
char* data = nullptr;
};
void leak_for_exception(){ // 如果不使用上面的方法,一个函数在执行的过程中
// 抛了异常,会导致资源释放的代码走不到
void* data = malloc(1000);
throw string("yes this is an exception");
free(data);
}
void leak_for_exception2(){ // 根据c++ primer 18.1 异常被抛出后,暂停当前函数的执行
// 然后再当前try块对应的catch块中找匹配的异常,若没找到
// 就去外层try-catch中找,若还是没有,就推出当前函数,去外层函数中找
// 此为“栈展开”
ExceptionSafe es;
throw string("yes this is an exception");// 这里抛异常之后,局部变量es会被自动销毁
}
void try_leak_func(){
try{
leak_for_exception();
}catch (string& s){
cout << s <<endl;
}
try{
leak_for_exception2();// “栈展开”的过程中,程序的执行会退出某些块,编译器会保证这些块
// 中的局部对象被销毁。
}catch (string& s){
cout << s <<endl;
}
}
int main(){
cout << "123" << endl;
Leak l; // 因为类写的不严谨 泄露100
try_leak_func(); // 第一次使用了异常不安全的函数,抛异常导致释放操作被跳过,泄露1000
// 第二次使用资源管理类来保护内存,抛异常之后没有发生泄露
}
valgrind检查报告:
valgrind --leak-check=full ./test
==4169== Memcheck, a memory error detector
==4169== Copyright (C) 2002-2017, and GNU GPL'd, by Julian Seward et al.
==4169== Using Valgrind-3.13.0 and LibVEX; rerun with -h for copyright info
==4169== Command: ./test
==4169==
123
Leak constructed.
yes this is an exception
ExceptionSafe constructed.
ExceptionSafe destroyed.
yes this is an exception
Leak destroyed.
==4169==
==4169== HEAP SUMMARY:
==4169== in use at exit: 1,100 bytes in 2 blocks
==4169== total heap usage: 9 allocs, 7 frees, 85,198 bytes allocated
==4169==
==4169== 100 bytes in 1 blocks are definitely lost in loss record 1 of 2
==4169== at 0x4C2FB0F: malloc (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==4169== by 0x10928E: Leak::Leak() (in /home/lee/share/CPP/t001/test)
==4169== by 0x10919A: main (in /home/lee/share/CPP/t001/test)
==4169==
==4169== 1,000 bytes in 1 blocks are definitely lost in loss record 2 of 2
==4169== at 0x4C2FB0F: malloc (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==4169== by 0x108F4D: leak_for_exception() (in /home/lee/share/CPP/t001/test)
==4169== by 0x109085: try_leak_func() (in /home/lee/share/CPP/t001/test)
==4169== by 0x10919F: main (in /home/lee/share/CPP/t001/test)
==4169==
==4169== LEAK SUMMARY:
==4169== definitely lost: 1,100 bytes in 2 blocks
==4169== indirectly lost: 0 bytes in 0 blocks
==4169== possibly lost: 0 bytes in 0 blocks
==4169== still reachable: 0 bytes in 0 blocks
==4169== suppressed: 0 bytes in 0 blocks
==4169==
==4169== For counts of detected and suppressed errors, rerun with: -v
==4169== ERROR SUMMARY: 2 errors from 2 contexts (suppressed: 0 from 0)