Talk:More C++ Idioms/Construct On First Use

Hi All,

The "construct on first use" idiom isn't thread-safe as documented here. The problem is that C++ compilers don't serialize the initialization code. This is discussed in great detail elsewhere: see Singleton Pattern or google "C++ concurrent static initialization".

In the first example, if two threads called Foo::bar concurrently, the following line could execute twice, concurrently:

static Bar *b = new Bar ;

Two Bar objects would be constructed, but of course b can only point to one, so the other one would be leaked. That may or may not be a problem, depending on what the Bar ctor does.

In the second example, Bar::Bar could be called concurrently on b. Again depending on what the constructor does, the results could range from benign to catastrophic.

Even if this pattern is coded in a thread-safe way, the problem of destruction order remains to be solved.

In any event, we should be able to come up with a solution that's less codey than the one given on the Wikipedia page I mentioned. Anyone interested in working on this?

-- Chris