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.
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 .
Maybe you should use std::call_once
found in <mutex>
.
Examples of how to use it here
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With