Threaded singleton in C ++ 11

I know this is the thread-safe way of implementing a singleton in C ++ 11:

Foo* getInst()
{
    static Foo* inst = new Foo(...);
    return inst;
}

      

I read in this answer that the following is also thread safe:

Foo& getInst()
{
    static Foo inst(...);
    return inst;
}

      

Is it really thread safe? Isn't it a problem that an instance of Foo will be allocated on the same frame stack and won't be allocated on the heap?

If it's thread-safe, is there a good reason to prefer each other?

+3


source to share


2 answers


Static variables are NOT allocated on the stack. In the first option, you have a static pointer (global variable) initialized with the memory obtained from the heap, and in the second, the entire 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 provide serialized access to a special variable that tells whether your global instances have already been initialized or not.

Your code:

Foo& getInst()
{
    static Foo inst(...);
    return inst;
}

      



will actually look like after 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 examples are thread safe.

+9


source


inst

in your example will not be allocated on the stack. It will be posted somewhere in the section .data

or .bss

. Otherwise, this static variable will not be able to live the entire time program, and therefore it cannot have the same value as it did before, every time you enter this function.



+4


source







All Articles