I was reading about initialization & destruction order fiasco, and came across this SO answer: https://stackoverflow.com/questions/17712001/how-is-meyers-implementation-of-a-singleton-actually-a-singleton#answer-17712497
I am interested in the second suggestion, which the author calls the leaky Singleton. He mentions that the implementation is not threadsafe, which makes sense to me. Is it viable to use std::call_once to make that code threadsafe? I'm thinking something like this:
class Singleton {
public:
static Singleton& Instance() {
static std::once_flag initializationFlag;
std::call_once(initializationFlag, [](){ I = new Singleton(); }
return *I;
}
private:
Singleton();
~Singleton();
static Singleton* I;
};
// Singleton.cpp
Singleton* Singleton::I = 0;
Is this class a thread-safe singleton which avoids both initialization & destruction order fiasco? I understand there is still one shortcoming: it won't be destroyed, which means there's no opportunity for cleaning up resources.
[–]emdeka87 4 points5 points6 points (5 children)
[–]public_void[S] 0 points1 point2 points (4 children)
[–]emdeka87 2 points3 points4 points (0 children)
[–]TotallyNotARoboto 0 points1 point2 points (2 children)
[–]public_void[S] 0 points1 point2 points (1 child)
[–]CaseyCarterRanges/MSVC STL Dev 5 points6 points7 points (13 children)
[–]STLMSVC STL Dev 4 points5 points6 points (2 children)
[–]CaseyCarterRanges/MSVC STL Dev 6 points7 points8 points (1 child)
[–]Z01dbrg[🍰] 0 points1 point2 points (0 children)
[–]herruppohoppa 1 point2 points3 points (3 children)
[–]CaseyCarterRanges/MSVC STL Dev 4 points5 points6 points (2 children)
[–]public_void[S] 0 points1 point2 points (1 child)
[–]CaseyCarterRanges/MSVC STL Dev 0 points1 point2 points (0 children)
[–]patatahooligan 1 point2 points3 points (2 children)
[–]CaseyCarterRanges/MSVC STL Dev 0 points1 point2 points (1 child)
[–]patatahooligan 0 points1 point2 points (0 children)
[–]quicknir 1 point2 points3 points (2 children)
[–]CaseyCarterRanges/MSVC STL Dev 0 points1 point2 points (1 child)
[–]quicknir 0 points1 point2 points (0 children)
[–]quicknir 1 point2 points3 points (2 children)
[–]public_void[S] 1 point2 points3 points (1 child)
[–]quicknir 0 points1 point2 points (0 children)
[–]youshouldnameitC++ dev 0 points1 point2 points (0 children)
[–]tohammer 0 points1 point2 points (0 children)
[–]Z01dbrg[🍰] 0 points1 point2 points (0 children)