There's a number of things the Wikipedia implementation does badly (or could at least have been done better)
- getInstance() returns a pointer. There's no reason whatsoever for this.
- The assignment
m_pSingleton = new CSingleton;
can be forgotten without a compile-time warning, resulting in a runtime segfault - The conditional
if(m_pSingleton == NULL)
(which should have been written asif(!m_pSingleton)
orif(m_pSingleton == 0)
anyway, read "The C++ Programming Language" by Stroustrup and realise that C and C++ are two different languages) can be forgotten resulting in confusing behavior
A much better solution looks like this:
#include
class SomeClass
{
private:
SomeClass(){ /* Do whatever */ };
public:
static SomeClass& get()
{
static SomeClass instance;
return instance;
}
void doStuff()
{ std::cout << "stuff\n"; }
};
int main()
{
SomeClass::get().doStuff();
SomeClass::get().doStuff();
return 0;
}
Let's see if my earlier comments on the Wikpedia example still apply:
- get() (the
getInstance()
equivalent, feel free to name this functiongetInstance()
) returns a reference, not a pointer. - If the initialisation (
static SomeClass instance;
) is forgotten, this will result in a compile-time error - There is no check, the code that makes sure the instance is only instantiated once is generated automatically by the C++ compiler
No comments:
Post a Comment