Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Standard library function for running a function only once

Is there some standard library function/class the behaviour of this lambda expression:

void some_func(int some_arg, float some_other_arg){
    static int do_once = ([](){
        // will be run once upon first function call but never again
        return 0; // dummy return value
    })();
    // will always run
}

It feels like such a hack to write this, but I can't think of another way of doing this other than simply calling the function in main, but what I'm actually doing depends upon template parameters and I need to keep it as generic as possible.

For context:
I register a function with atexit for every different template parameter, but only once: the first time it is called.

like image 354
RamblingMad Avatar asked Aug 26 '14 07:08

RamblingMad


People also ask

How do I run code only once?

To run a function only once:Declare a global variable and initialize it to False . Change the value of the global variable to True in the function. Only run the code in the function if the global variable is set to False .


2 Answers

Maybe you should use std::call_once found in <mutex>.
Examples of how to use it here

like image 145
Kiroxas Avatar answered Oct 21 '22 18:10

Kiroxas


I have gone with the std::call_once option, and it works great.

To do so I have re-written my function like so:

template<typename T>
void my_function(){
    static std::once_flag once;

    // function body (may return)

    // only called if rest of function successful
    std::call_once(once, [](){/* special sauce */});
}

@cdhowie, I don't think you quite understand what I mean by static, it's almost the opposite of global.

like image 40
RamblingMad Avatar answered Oct 21 '22 18:10

RamblingMad