Is this way to create a static stream of instances safe?

I have the following C ++ code example:

class Factory
{
public:
    static Factory& createInstance()
    {
        static Factory fac;
        return fac;
    }

private:
    Factory() 
    {
        //Does something non-trivial
    }
};

Suppose that createInstanceis called by two threads at the same time. Will the resulting object be created correctly? What happens if the second thread enters the call createInstancewhen the first thread is in the constructor Factory?

+5
source share
4 answers

No, as long as this does not apply to the standard.

The problem is that the C ++ standard has not mentioned the stream so far, C ++ 0x integrates this, but is not standard yet.

, , , , , . , , .

, , . - , , , , .

+5

, , , , . InterlockedCompareExchange(), , , null.

+2

, ! , , main(), createInstance , . ISO ++ , main(): , main, , main(). , ISO ++ , , , .

0

( ) threadsafe.

, . , , Factory, Factory, .

, Factory , - .

, Factory ( -), .

0

All Articles