Lazy Initialization
suggest changeThis example has been lifted from the Q & A section here:http://stackoverflow.com/a/1008289/3807729
See this article for a simple design of a lazily evaluated singleton that is destroyed at the end of the program:
The classic lazy evaluated and correctly destroyed singleton.
class S
{
public:
static S& getInstance()
{
static S instance; // Guaranteed to be destroyed.
// Instantiated on first use.
// Thread-safe since C++11; not in C++03.
return instance;
}
private:
S() {}; // Constructor? (the {} brackets) are needed here.
// C++03 alternative: declare these and do not define them.
// A class uses that technique or the deletions below, not both.
// S(S const&);
// void operator=(S const&);
// C++11: delete the operations that must not be used.
public:
S(S const&) = delete;
void operator=(S const&) = delete;
// Note: Scott Meyers mentions in his Effective Modern
// C++ book, that deleted functions should generally
// be public as it results in better error messages
// due to the compilers behavior to check accessibility
// before deleted status
};
See this article about when to use a singleton: (not often)
http://stackoverflow.com/questions/86582/singleton-how-should-it-be-used
See these two articles about initialization order and how to cope:
http://stackoverflow.com/questions/211237/c-static-variables-initialisation-order/211307#211307
See this article describing lifetimes:
http://stackoverflow.com/questions/246564/what-is-the-lifetime-of-a-static-variable-in-a-c-function
See this article that discusses some threading implications to singletons:
See this article that explains why double checked locking will not work on C++: