Recently I've bumped into a realization/implementation of the Singleton design pattern for C++. It has looked like this (I have adopted it from the real life example):
// a lot of methods are omitted here
class Singleton
{
public:
static Singleton* getInstance( );
~Singleton( );
private:
Singleton( );
static Singleton* instance;
};
From this declaration I can deduce that the instance field is initiated on the heap. That means there is a memory allocation. What is completely unclear for me is when exactly the memory is going to be deallocated? Or is there a bug and memory leak? It seems like there is a problem in the implementation.
My main question is, how do I implement it in the right way?
@sbi - Only a Sith deals in absolutes. Can the vast majority of problems be solved without Singletons? Absolutely. Do Singletons cause problems of their own? Yes. However, I can't honestly say that they'rebad, since design is all about considering the tradeoffs and understanding the nuances of your approach. –
derekerdmannJul 28 '11 at 20:10
7
@derekerdmann: I didn't say you never need a global variable (and when you need one, a Singletonsometimes is better). What I said is that they should be used as little as possible. Glorifying Singleton as a valuable design pattern gives the impression it's good to use it, rather than that it is a hack, making code hard to understand, hard to maintain, and hard to test. This is why I posted my comment. None of what you said so far contradicted this. –
sbiJul 29 '11 at 13:26
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.
return instance;
}
private:
S() {}; // Constructor? (the {} brackets) are needed here.
// C++ 03
// ========
// Dont forget to declare these two. You want to make sure they
// are unacceptable otherwise you may accidentally get copies of
// your singleton appearing.
S(S const&); // Don't Implement
void operator=(S const&); // Don't implement
// C++ 11
// =======
// We can use the better technique of deleting the methods
// we don't want.
S(S const&) = delete;
void operator=(S const&) = delete;
};
Recently I've bumped into a realization/implementation of the Singleton design pattern for C++. It has looked like this (I have adopted it from the real life example):// a lot of methods are omitted