如何确保一个函数仅被调用一次 [英] How to make sure a function is only called once

查看:66
本文介绍了如何确保一个函数仅被调用一次的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个名为caller的函数,它将调用一个名为callee的函数:

Suppose I have a function named caller, which will call a function named callee:

void caller()
{
    callee();
}  

现在在应用程序中可能多次调用了调用方,并且您想确保被调用方仅被调用一次.(有点懒惰的初始化),您可以使用标志来实现它:

Now caller might be called many times in the application, and you want to make sure callee is only called once. (kind of lazy initialization), you could implement it use a flag:

void caller()
{
    static bool bFirst = true;
    if(bFirst)
    {
        callee();
        bFirst = false;
    }
}

对此我的看法是,它需要更多代码,并且在每次调用函数调用程序时都需要再进行一次检查.
对我来说,更好的解决方案如下:(假设被调用者返回int)

My opinion for this is it needs more code, and it needs one more check in every call of function caller.
A better solution to me is as follow: (suppose callee returns int)

void caller()
{
    static int ret = callee();
}  

但是如果被调用者返回void,这将无法处理,我的解决方案是使用逗号表达式:

But this can't handle the case if callee returns void, my solution is using the comma expression:

void caller()
{
    static int ret = (callee(), 1);
}  

但是,这样做的问题是逗号表达不常用,人们在看到这一行代码时可能会感到困惑,从而导致维护问题.

But the problem with this is that comma expression is not popular used and people may get confused when see this line of code, thus cause problems for maintainance.

您有什么好主意来确保一个函数仅被调用一次?

Do you have any good idea to make sure a function is only called once?

推荐答案

线程安全:

    static boost::once_flag flag = BOOST_ONCE_INIT;
    boost::call_once([]{callee();}, flag);  

这篇关于如何确保一个函数仅被调用一次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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