Home > Software engineering >  How many times are arguments calculated in multithreaded function-scope static variable initializati
How many times are arguments calculated in multithreaded function-scope static variable initializati

Time:10-24

Suppose we have a following function, which is executed by multiple threads at the same time:

void foo()
{
    static SomeClass s{get_first_arg(), get_second_arg()};
}

My question is how many times will get_first_arg and get_second_arg be executed -- exactly once, or ThreadCount times, or is it unspecified/implementation-defined behavior?

CodePudding user response:

The local static variable s initialized only once and the first time control passes through the declaration of that variable. This can be seen from static local variable's documentation:

Variables declared at block scope with the specifier static have static storage duration but are initialized the first time control passes through their declaration (unless their initialization is zero- or constant-initialization, which can be performed before the block is first entered). On all further calls, the declaration is skipped.

(emphasis mine)

This in turn means that the arguments get_first_arg() and get_second_arg() will be evaluated only once.


  • Related