How maintainable are these hacks in the long run? Is there firm theoretical basis, if yes, then sources?
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.