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

标签 c++ exception raii exception-safety

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/

相关文章:

java - java 程序中的 NoClassDefFoundError

c++ - RAII与std::function

ios - 你能使用 Swift ARC 快速释放稀缺资源(文件描述符、网络套接字)吗?

c++ - 是否可以保证不会在 C++ 中优化执行内存写入的代码?

c++ - Boost图分割错误

python - 异常处理

c++ - 重构为 RAII 时会遇到问题吗?

c++ - circshift 方面的 fftshift/ifftshift

c++ - 使用清晰的代码行异步调用插槽,无需连接到它

c++ - 抛出 C++ 函数声明会排除抛出其他异常吗?