[SG10] Missing feature macro for threadsafe function local statics

Daniel Krügler daniel.kruegler at gmail.com
Tue Feb 21 21:28:33 CET 2017


Thread-safe initialization of static local function variables is part
of C++11, via

http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2008/n2660.htm

but

(a) at least some implementations still do not support them, or
(b) provide means (outside of the spec) that allow to disable this
functionality (gcc: --fno-threadsafe-statics, Visual Studio 2015:
/Zc:threadSafeInit-).

The compilers I am aware of both don't provide a vendor specific
feature macro to detect this situation.

I would therefore strongly vote for a feature macro that describes the
presence of that functionality, because user code can usually defend
against this missing feature by means of std::call_once. Here is
therefore a minimalistic example code hopefully suitable for a future
revision of p0096 (The example also shows my current feature macro
name suggestion as "__cpp_threadsafe_static_init"):

Thingy& get_thing()
{
#ifndef __cpp_threadsafe_static_init
    [...]
    static std::once_flag flag;
    std::call_once(flag, init::get);
    return init::get();
#else
    static Thingy result;
    return result;
#endif
}

Thanks,

- Daniel


More information about the Features mailing list