Home >Backend Development >C++ >Is Meyer's Singleton Implementation Truly a Singleton, and How Does it Compare to Thread-Safe Alternatives?
The Meyer's Singleton implementation, presented as static Singleton& instance(), raises questions regarding its singleton functionality.
The singleton nature stems from the static keyword. Static storage duration for local variables means only one instance exists throughout the program.
Consider this equivalent pseudocode (not actual C 98 code):
static bool __guard = false; static char __storage[sizeof(Singleton)]; Singleton& Instance() { if (!__guard ) { __guard = true; new (__storage) Singleton(); } return *reinterpret_cast<Singleton*&>(__storage); }
This roughly encapsulates the behavior of the original implementation.
In the actual C 11 implementation, a guard variable is used for each static, acting as a barrier for threads.
Both implementations enforce singleton integrity, but differ in thread handling and code complexity.
Meyer's Implementation:
Wikipedia Implementation:
The Meyer's implementation is indeed a Singleton due to the static storage duration preventing multiple instantiations. The choice between the two implementations depends on the specific application and multithreading considerations.
The above is the detailed content of Is Meyer's Singleton Implementation Truly a Singleton, and How Does it Compare to Thread-Safe Alternatives?. For more information, please follow other related articles on the PHP Chinese website!