问题
Say we have some external linkage using the extern keyword.
I have (in class1.cpp):
MyClass* myClassVar = NULL;
The constructor initializes the above, and destructor deletes.
Then in class2.cpp and class3.cpp there is:
extern MyClass* myClassVar;
These classes use myClassVar (doing the usual null checks etc).
Would a Singleton be preferred? (I know globals are bad etc, and a Singleton is just syntax sugar). Is there an advantage to change the above code to the below?
static Singleton& getInstance()
{
static Singleton instance;
return instance;
}
Then all classes will do:
Singleton::getInstance()
回答1:
Global variables suffer from the initialisation order fiasco. Globals in separate translation units are initialised in an unspecified order, so you get undefined behaviour if one refers to another in its constructor.
Static variables in a function scope are initialised the first time the function is called, which (more or less) solves the initialisation order problem.
However, more subtle problems remain; in particular, it is still possible to access the object after it has been destroyed, and there is some overhead to ensure thread-safe initialisation (and, in older compilers, initialisation might not be thread-safe at all). There is no completely safe way to manage globally accessible objects of non-trivial types, and my advice would be to avoid them altogether if possible.
回答2:
Since you say you already know the downfalls of any type of globals, the only advantage is that you limit the instances of the class to 1, as opposed to using extern
, where you can just as well define multiple variables of that kind.
来源:https://stackoverflow.com/questions/12247912/extern-vs-singleton-class