Is initialization of local static function-object

2019-04-06 22:50发布

问题:

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);
}

回答1:

"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).



回答2:

As Bo says, the current C++ standard demands that static variable initialization not introduce a data race. (This is of course only relevant to the dynamic initialization phase.) For example, if you look at the output of GCC when initializing a static variable, you'll indeed find calls to __cxa_guard_acquire, __cxa_guard_release and __cxa_guard_abort surrounding the initialization.

The Itanium C++ ABI actually formalizes the mechanism.