Meyers' Singleton Implementation: Unveiling the Singletonness
Question:
How is Meyers' lazy initialized implementation of Singleton in C , as seen below, actually a Singleton pattern?
static Singleton& instance() { static Singleton s; return s; }
Answer:
To understand the Singletonness of Meyers' implementation, it's important to recognize the key characteristic: static storage duration.
In C , local variables declared within a function have static storage duration if they are declared static. This means that only one instance of that variable exists for the entire program, regardless of how many times the function is called.
In Meyers' implementation, the static Singleton s variable has static storage duration. Therefore, only one instance of Singleton can ever be created, enforcing the Singleton pattern.
To provide a clearer understanding, let's break down the code under the hood:
// Global guard variable static bool __guard = false; // Static storage for the Singleton static char __storage[sizeof(Singleton)]; Singleton& Instance() { if (!__guard) { __guard = true; new (__storage) Singleton(); } return *reinterpret_cast<Singleton*>(__storage); }
This implementation is similar to Meyers' original proposal but includes thread safety mechanisms. The __guard variable ensures that the Singleton is initialized only once, even if accessed concurrently from multiple threads.
Comparison with Other Implementations:
Compared to other Singleton implementations, Meyers' version offers the following pros and cons:
Pros:
Cons:
Conclusion:
Meyers' lazy initialized Singleton implementation leverages static storage duration to ensure that only one instance of the Singleton exists throughout the program, making it a valid Singleton pattern. While other implementations may offer advantages in terms of performance or memory management, Meyers' version remains a reliable and widely used Singleton design.
The above is the detailed content of Is Meyers' Lazy Initialized Singleton Implementation Truly a Singleton?. For more information, please follow other related articles on the PHP Chinese website!