如何在函数出口上运行清除代码? [英] How do I run a cleanup code on the function exit?

查看:92
本文介绍了如何在函数出口上运行清除代码?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

C++ classes provide RAII idiom. Therefore you don't have to care about exceptions:

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

    // Do some work        
}

但是如果您(由于某些原因)必须使用某些纯C API,您必须在其周围创建C ++包装程序,或使用try / catch块

But if you have (for some reasons) to use some pure C API, you have either to create C++ wrappers around it or to use try/catch blocks

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);
}

即使您将C ++类与RAII习惯用法结合使用,有时也必须编写一个具有强大异常安全保障的代码:

Even if you use C++ classes with RAII idiom, sometimes you have to write a code with strong exception-safety guaranty:

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 ,但是在功能范围内……

Is there any way to force to run some cleanup code at function exit? Something similar to atexit, but in a function scope...

有没有办法运行一些回滚代码如果不使用嵌套的try / catch块就出现异常?

Is there any way to run some rollback code in case of exception without using nested try/catch blocks?

我想要一些可以像这样运行的运算符或函数:

I would like to have some operators or functions that would work like this:

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
}

如果可以创建此类功能,是否有任何避免使用这些功能的理由?其他编程语言中是否有这样的构造?

If it is possible to create such functions, are there any reasons to avoid using them? Are there such constructs in other programming languages?

推荐答案

ScopeGuard是您的正确选择。它基本上会调用您在析构函数中指定的函数。

ScopeGuard is the right choice for you. It basically calls the function you specify at destructor.

因此您的代码可以是:

void your_function() {
  scope_guard guard = [&vector]() {
    vector.pop_back();
  };
  // your code
  guard.dismiss(); // success
}

这篇关于如何在函数出口上运行清除代码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆