Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is initialization of local static function-object thread-safe?

The following two functions produce different assemblies, which tells me they're different. Can someone tell me in what way they are different? And is the function local static variable initialization in func2 thread-safe or not? If the answer depends on the compiler, I'd like to know how would the most common compilers behave with func2.

int func1(int val)
{
    const auto impl = [](int v)
    {
        return v * 10;
    };

    return impl(val);
}

int func2(int val)
{
    static const auto impl = [](int v)
    {
        return v * 10;
    };

    return impl(val);
}
like image 712
zeroes00 Avatar asked Aug 13 '12 17:08

zeroes00


1 Answers

"The most common compilers" probably differ on this, as they have not all the same support for C++11.

In C++11 the initialization of the static variable is thread safe. In C++03 it is not (as there aren't any threads according to the standard).

like image 91
Bo Persson Avatar answered Sep 24 '22 23:09

Bo Persson