Singleton with an object which throws in the ctor - accessing again?

[stmt.dcl]/4: Dynamic initialization of a block-scope variable with static storage duration or thread storage duration is performed the first time control passes through its declaration; such a variable is considered initialized upon the completion of its initialization. If the initialization exits by throwing an exception, the initialization is not complete, so it will be tried again the next time control enters the declaration. [..]

No need to "guess"; you could put a std::cout trace inside MyInstance::MyInstance() and call getInstance() twice. 😊

Also no need for smart pointers; the object either exists or it doesn't, and there's no way to proceed inside getInstance() after the declaration without the object existing, because you threw an exception!

By the way, it's std::runtime_error, not std::runtime_exception.


If the constructor throws the object is not initialized. So if control passes through getInstance again, initialization will be performed again as well.

[stmt.dcl] (emphasis mine)

4 Dynamic initialization of a block-scope variable with static storage duration or thread storage duration is performed the first time control passes through its declaration; such a variable is considered initialized upon the completion of its initialization. If the initialization exits by throwing an exception, the initialization is not complete, so it will be tried again the next time control enters the declaration. If control enters the declaration concurrently while the variable is being initialized, the concurrent execution shall wait for completion of the initialization. If control re-enters the declaration recursively while the variable is being initialized, the behavior is undefined.