C++ allows the code to be executed only once

I searched for this information today, and then I simply rewritten a macro to achieve it:

/*** 宏函数-括号中的code代码只执行一次 ***/
#define once_run(code) {        \
    static auto tmp = [&](){    \
        code;                   \
        return 0;               \
    }();                        \
    (void)tmp;                  \
}

The actual test found that there are several places to pay attention to:

  1. The "&" in the lambda function cannot be omitted, otherwise the code segment in the brackets cannot capture the variables defined outside the function;
  2. The "()" at the end of the lambda function cannot be omitted, otherwise the static variable tmp will not be initialized, that is, the code code will not be executed once;
  3. The last (void)tmp has no effect, just to prevent the compiler from alarming, otherwise it will report that the defined variable is not used

Test code:

#include <iostream>
#include <unistd.h>
using namespace std;

#define once_run(code) {        \
    static auto tmp = [&](){    \
        code                    \
        return 0;               \
    }();                        \
    (void)tmp;                  \
}
int main(){
    
    
    int a = 1;
    while (1) {
    
    
        once_run(a++;)
        cout<<"a = "<<a<<endl;
        sleep(1);
    }
    return 0;
}

result:
Insert picture description here

Decided to start using CSDN to save my study notes. It was the first time to write an article in CSDN and slipped away.

Reference [1] provides another macro for multi-threading, which is also recorded here:

#define ONCE_RUN(code) {                                    \
    static int _done;                                       \
    if (!_done) {                                           \
        if (__sync_bool_compare_and_swap(&_done, 0, 1)) {   \
            code                                            \
        }                                                   \
    }                                                       \
}

If multithreading is not involved, it seems better to use the above one in theory, because there is no need to judge each if.

Reference article

https://www.cnblogs.com/life2refuel/p/8283435.html
https://www.cnblogs.com/cheungxiongwei/p/13498135.html

Guess you like

Origin blog.csdn.net/junh_tml/article/details/114675327