2

In many places i have code for one time initialization as below

int callback_method(void * userData)
{
   /* This piece of code should run one time only */
   static int init_flag = 0;
   if (0 == init_flag)
   {
     /* do initialization stuff here */
     init_flag = 1;
   }

   /* Do regular stuff here */

   return 0;
}

just now I started using c++11. Is there a better way to replace the one time code with c++11 lambda or std::once functionality or any thing else?.

rameshrgtvl
  • 243
  • 2
  • 16
  • 1
    http://stackoverflow.com/questions/4173384/how-to-make-sure-a-function-is-only-called-once I think the second answer is good too. – Yves Dec 09 '16 at 16:12

2 Answers2

3

You can encapsulate your action to static function call or use something like Immediately invoked function expression with C++11 lambdas:

int action() { /*...*/ }
...
static int temp = action();

and

static auto temp = [](){ /*...*/ }();

respectively.

And yes, the most common solution is to use std::call_once, but sometimes it's a little bit overkill (you should use special flag with it, returning to initial question).

With C++11 standard all of these approaches are thread safe (variables will be initialized once and "atomically"), but you still must avoid races inside action if some shared resources used here.

Trollliar
  • 826
  • 5
  • 14
2

Yes - std::call_once, see the docs on how to use this: http://en.cppreference.com/w/cpp/thread/call_once

Nim
  • 33,299
  • 2
  • 62
  • 101
  • Using std::call_once I see a similar implementaion, instead of static variable std::once_flag is used. std::once_flag flag; void testMethod2() { std::cout << __PRETTY_FUNCTION__ << std::endl; } int main() { std::call_once(flag, testMethod2); std::call_once(flag, testMethod2); return 0; } – rameshrgtvl Dec 09 '16 at 13:28