离开范围时调用函数 [英] call function when leaving scope

查看:73
本文介绍了离开范围时调用函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

离开范围时自动调用函数的最优雅的解决方案是什么?
我目前的方法(见下文)有效,但我想写一个自定义脚本应该有一些更一般的方法

What is the most elegant solution for calling a function automatically when leaving a scope? My current approach (see below) works but I guess there should be something more general as writing a custom class for this.

#include <iostream>
#include <functional>

using namespace std;

class DoInDtor
{
public:
    typedef function<void()> F;
    DoInDtor(F f) : f_(f) {};
    ~DoInDtor() { f_(); }
private:
    F f_;
};

void foo()
{
    DoInDtor byeSayerCustom([](){ cout << "bye\n"; });

    auto cond = true; // could of course also be false
    if ( cond )
        return;

    return;
}

int main()
{
    foo();
}

当然,有人可能会滥用std :: unique_ptr及其自定义删除器,但是由于我并不是在这里真正获得资源,就代码可读性而言,这对我来说听起来也不是很好。有建议吗?

Sure, one could abuse std::unique_ptr and its custom deleter, but since I am not really acquiring a resource here, that does not sound great to me either in terms of code readability. Any suggestions?

推荐答案

以这种方式使用构造函数/析构函数是解决此类排序问题的常用方法。我已经将它用于锁(构造函数获取锁,析构函数释放它)和日志记录目的(构造函数在构造上打印一些东西,在析构函数上打印一些破坏,从而为项目提供了一个不错的调用图-在后一种情况下,使用宏也可以获得 __ FILE __ __ LINE __ 存储在对象中,因此我们可以看到构造函数的调用位置[几乎不可能做到这一点的析构函数,但通常可以看到该构造函数并弄清楚析构函数的调用位置])。

Using a constructor/destructor in this way is a common way to solve this sort problem. I have used it for both locks (constructor takes lock, destructor releases it) and logging purposes (constructor prints something on construction, and destructor prints on destruction, giving a nice callgraph of a project - in the latter case, using macros to also get __FILE__ and __LINE__ store in the object, so we can see where the constructor was called [it's almost impossible to do this for the destructor, but typically it's possible to see the constructor and make out where the destructor gets called]).

这篇关于离开范围时调用函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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