"thread-safe singleton in c++11" Code Answer

2

static variables are not allocated on the stack. in the first variant you have a static pointer (a global variable) initialized with a memory obtained from the heap, while in the second one you have whole static object.

both versions use internal compiler guards (namely __cxa_guard_acquire() and __cxa_guard_release(), which are functionally equivalent to mutex::lock() and mutex::unlock()) to ensure serialized access to a special variable that tells whether or not your global instances are already initialized or not.

your code:

foo& getinst()
{
    static foo inst(...);
    return inst;
}

will actually look like that after the compilation:

foo& getinst()
{
    static foo inst; // uninitialized - zero
    static guard instguard; // zero

    if (is_initialized(instguard) == false)
    {
        __cxa_guard_acquire(instguard);
        // do the initialization here - calls foo constructor
        set_initialized(instguard);
        __cxa_guard_release(instguard);
    }

    return inst;
}

so both of your exampes are thread safe.

By Rethic on March 31 2022

Answers related to “thread-safe singleton in c++11”

Only authorized users can answer the Search term. Please sign in first, or register a free account.