Useful C++ template magic. Hiding nasty global static’s
In C++, often there is a need to provide and support single instance of certain class, accessible on demand from anywhere in the program. That is encyclopedic example given in many books promoting singleton pattern. For instance, if your program has a log file, it is strongly recommended that you make a class that encapsulates all logging and make it singleton. This approach, without any doubts, is much much better than making global static instance of the logger and then referring to it from whatever you need as it reduces number of cross-dependencies, an issue that stays among the most bad techniques making code less maintainable.
This is easy to understand – while there is nothing wrong in static variable, even in global static variable, we must ensure that it is initialized before it is used first, which is especially important if the object has to be created dynamically. And this is the problem Singleton pattern solves.
Take the example
// SomeSourceFile.h #include "CoffeePlantation.h" static CoffeePlantation g_Plantation; // SomeSourceFile.cpp #include "SomeSourceFile.h" // Initialize the instance g_Plantation = CoffeePlantation();