gpt4 book ai didi

c++ - 如何在函数导出运行清理代码?

转载 作者:太空宇宙 更新时间:2023-11-04 12:51:32 25 4
gpt4 key购买 nike

C++ 类提供 RAII 习惯用法。因此您不必关心异常:

void function()
{
// The memory will be freed automatically on function exit
std::vector<int> vector(1000);

// Do some work
}

但如果您(出于某些原因)必须使用一些纯 C API,则必须围绕它创建 C++ 包装器或使用 try/catch block

void function()
{
int *arr = (int*)malloc(1000*sizeof(int));
if (!arr) { throw "cannot malloc"; }

try
{
// Do some work
}
catch (...)
{
free(arr); // Free memory in case of exception
throw; // Rethrow the exception
}

// Free memory in case of success
free(arr);
}

即使您使用带有 RAII 习惯用法的 C++ 类,有时您也必须编写具有强异常安全保证的代码:

void function(std::vector<const char*> &vector)
{
vector.push_back("hello");
try
{
// Do some work

vector.push_back("world");
try
{
// Do other work
}
catch (...)
{
vector.pop_back(); // Undo vector.push_back("world")
throw; // Rethrow the exception
}
}
catch (...)
{
vector.pop_back(); // Undo vector.push_back("hello");
throw; // Rethrow the exception
}
}

但是这些结构非常笨重。

有没有办法强制在函数退出时运行一些清理代码?类似于 atexit,但在函数范围内...

有没有办法在不使用嵌套的 try/catch block 的情况下运行一些回滚代码以防出现异常?

我想要一些像这样工作的运算符或函数:

void function(std::vector<const char*> &vector)
{
int *arr = malloc(1000*sizeof(int));
onexit { free(arr); }

vector.push_back("hello");
onexception { vector.pop_back(); }

// Do some work

vector.push_back("world");
onexception { vector.pop_back(); }

// Do other work
}

如果可以创建这样的函数,是否有任何理由避免使用它们?其他编程语言中是否有这样的结构?

最佳答案

我已经创建了实现此功能的宏。它们生成一个局部变量,该变量使用 C++11 lambda 函数在析构函数中运行清理代码。 std::uncaught_exception 函数用于检查当前是否有异常抛出。创建变量本身不应抛出任何异常,因为使用通过引用捕获所有变量的 lambda 来创建变量(此类 lambda 不会在复制/移动构造函数中抛出异常)。

#include <exception>

// An object of the class below will run an arbitrary code in its destructor
template <bool always, typename TCallable>
class OnBlockExit
{
public:
TCallable m_on_exit_handler;

~OnBlockExit()
{
if (always || std::uncaught_exception())
{ m_on_exit_handler(); }
}
};

// It is not possible to instantiate an object of the 'OnBlockExit' class
// without using the function below: https://stackoverflow.com/a/32280985/5447906.
// Creating of an object of the 'OnBlockExit' class shouldn't throw any exception,
// if lambda with all variables captured by reference is used as the parameter.
template <bool always, typename TCallable>
OnBlockExit<always, TCallable> MakeOnBlockExit(TCallable &&on_exit_handler)
{
return { std::forward<TCallable>(on_exit_handler) };
}

// COMBINE is needed for generating an unique variable
// (the name of the variable contains the line number:
// https://stackoverflow.com/a/10379844/544790)
#define COMBINE1(X,Y) X##Y
#define COMBINE(X,Y) COMBINE1(X,Y)

// ON_BLOCK_EXIT generates a variable with the name
// in the format on_block_exit##__LINE__
#define ON_BLOCK_EXIT(always, code) \
auto COMBINE(on_block_exit,__LINE__) = MakeOnBlockExit<always>([&]()code)

// Below are target macros that execute the 'code' on the function exit.
// ON_FINALLY will allways execute the code on the function exit,
// ON_EXCEPTION will execute it only in the case of exception.
#define ON_EXCEPTION(code) ON_BLOCK_EXIT(false, code)
#define ON_FINALLY(code) ON_BLOCK_EXIT(true , code)

这是一个如何使用这些宏的例子:

void function(std::vector<const char*> &vector)
{
int *arr1 = (int*)malloc(800*sizeof(int));
if (!arr1) { throw "cannot malloc arr1"; }
ON_FINALLY({ free(arr1); });

int *arr2 = (int*)malloc(900*sizeof(int));
if (!arr2) { throw "cannot malloc arr2"; }
ON_FINALLY({ free(arr2); });

vector.push_back("good");
ON_EXCEPTION({ vector.pop_back(); });

auto file = fopen("file.txt", "rb");
if (!file) { throw "cannot open file.txt"; }
ON_FINALLY({ fclose(file); });

vector.push_back("bye");
ON_EXCEPTION({ vector.pop_back(); });

int *arr3 = (int*)malloc(1000*sizeof(int));
if (!arr3) { throw "cannot malloc arr3"; }
ON_FINALLY({ free(arr3); });

arr1[1] = 1;
arr2[2] = 2;
arr3[3] = 3;
}

所有清理代码都以相反的顺序执行(顺序与 ON_FINALLY/ON_EXCEPTION 宏在函数中出现的顺序相反)。仅当控制超出相应的 ON_FINALLY/ON_EXCEPTION 宏时,才会执行清理代码。

检查以下链接以查看演示程序执行的输出:http://coliru.stacked-crooked.com/a/d6defaed0949dcc8

关于c++ - 如何在函数导出运行清理代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48842770/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com