How to execute a piece of code only once?

后端 未结 8 836
隐瞒了意图╮
隐瞒了意图╮ 2020-12-01 04:35

I have an application which has several functions in it. Each function can be called many times based on user input. However I need to execute a small segment of the code wi

8条回答
  •  萌比男神i
    2020-12-01 05:13

    Compact version using lambda function:

    void foo()
    {
        static bool once = [](){
            cout << "once" << endl;
            return true;
        } ();
        cout << "foo" << endl;
    }
    

    Code within lambda function is executed only once, when the static variable is initialized to the return value of lambda function. It should be thread-safe as long as your compiler support thread-safe static initialization.

提交回复
热议问题