The lazy initialization example is a classic algorithm. Usually concurrency hackers rediscover it from first principles. It's easy to maintain because the concurrency protocol it uses is easy to understand. Here's how I'd write it:
template<typename T, typename... Args>
void constructSingleton(Atomic<T*>& singletonRef, Args&&... args)
{
for (;;) {
T* oldValue = singletonRef.load();
if (oldValue)
return oldValue;
T* newValue = new T(std::forward<Args>(args)...);
if (singletonRef.compareExchangeWeak(nullptr, newValue))
return newValue;
delete newValue;
}
}
This works so long as the singletons are happy to be deleted. I'm assuming that's true here.