What is the lifetime of a static variable in a C++ function?

后端 未结 5 1312
渐次进展
渐次进展 2020-11-22 03:32

If a variable is declared as static in a function\'s scope it is only initialized once and retains its value between function calls. What exactly is its lifetim

5条回答
  •  天涯浪人
    2020-11-22 04:01

    Motti is right about the order, but there are some other things to consider:

    Compilers typically use a hidden flag variable to indicate if the local statics have already been initialized, and this flag is checked on every entry to the function. Obviously this is a small performance hit, but what's more of a concern is that this flag is not guaranteed to be thread-safe.

    If you have a local static as above, and foo is called from multiple threads, you may have race conditions causing plonk to be initialized incorrectly or even multiple times. Also, in this case plonk may get destructed by a different thread than the one which constructed it.

    Despite what the standard says, I'd be very wary of the actual order of local static destruction, because it's possible that you may unwittingly rely on a static being still valid after it's been destructed, and this is really difficult to track down.

提交回复
热议问题