This post is what I just read.
The way he implements Singleton in C++ confuses me. I got several Questions about it and here is his code:
template<typename T>
class Singleton {
public:
static T& getInstance() { //Question 1
return instance;
}
private:
static T instance;
};
class DebugLog : public Singleton<DebugLog> { //Question 2
public:
void doNothing() {}
};
Question
-
I think we should put the
static T& getInstance()‘s definition outside of the class body, right? -
He tries to make
class DebugLoga singleton class, but when he inheritsSingleton<DebugLog>, theDebugLogdoesn’t already exist, right? If right, then how can the template classSingletoninstantiate an un-existent class?
the class, and make the code easier to read and to maintain. In this
case, however, the complete class is small enough that the difference
isn’t very great, and of course, because we’re dealing with a template,
the actual definition still has to be included in every translation unit
which uses it.
The C++ standard doesn’t speak of “existence” with regards to classes (or anything
else). At the point of template instantiation, name lookup finds
DebugLog, and finds that it is a class (thus, a type). At that point,it is an incomplete type, and there are only limited things you can do
with an incomplete type. If the class template which is instantiated
doesn’t do anything that requires a complete type (and
Singletondoesn’t), then there is no problem. (Note that only the class
definition is instantiated at this point; class member functions will
not be instantiated until they are used.)
I might add that there is still one important thing missing from the
code you posted: there is no definition for the declaration
Singleton::instance. You still need to add a:somewhere.