Ok, I should simply tell that I want to make a base Singleton class that I can inherit from, and the way I want to achieve that is by a template.
In order to avoid memory leaks, I do not use directly a pointer to the instance, but a private class that will handle deleting the pointer.
Here is my actual code (not working) :
template <typename T> class Singleton
{
private:
class PointerInstance
{
private:
T* instance;
public:
PointerInstance() : instance(0) {}
~PointerInstance() { delete instance; } // no memory leak !
T* Get()
{
if ( !instance ) {
instance = new T();
}
return instance;
}
};
static PointerInstance PInstance;
public:
static T* pGetInstance(void)
{
return PInstance.pGet();
};
protected:
Singleton(void){};
~Singleton(void){};
};
And here is what a typical derived class declaration should look like :
class Child : public Singleton<Child>
{
friend class Singleton<Child>;
Child();
// etc...
};
Basically what is lacking is the instance of PInstance for each T class I make as a Singleton.
My question is : is there a way to do this once and for all with a few generic lines of code in the Singleton.h containing the code above, or do I have no other choice but to add a few specific lines of code for each derived class ?
(Bonus : is there a better way to do a Singleton class in C++ ?)