Most elegant way to write a one-shot 'if'

前端 未结 9 2192
情话喂你
情话喂你 2020-12-22 21:51

Since C++ 17 one can write an if block that will get executed exactly once like this:

#include 

        
9条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-22 22:12

    While using std::exchange as suggested by @Acorn is probably the most idiomatic way, an exchange operation is not necessarily cheap. Although of course static initialization is guaranteed to be thread-safe (unless you tell your compiler not to do it), so any considerations about performance are somewhat futile anyway in presence of the static keyword.

    If you are concerned about micro-optimization (as people using C++ often are), you could as well scratch bool and use int instead, which will allow you to use post-decrement (or rather, increment, as unlike bool decrementing an int will not saturate to zero...):

    if(static int do_once = 0; !do_once++)
    

    It used to be that bool had increment/decrement operators, but they were deprecated long ago (C++11? not sure?) and are to be removed altogether in C++17. Nevertheless you can decrement an int just fine, and it will of course work as a Boolean condition.

    Bonus: You can implement do_twice or do_thrice similarly...

提交回复
热议问题