[Dev-C++] singleton pattern implementation.
Open Source C & C++ IDE for Windows
Brought to you by:
claplace
|
From: Laura L. <lau...@gm...> - 2007-09-27 11:09:44
|
Hello,
I have a question about the next implementation of the singleton patter, if
I don't do "delete sc1" in main, is there a memory leak? the problem is
that if I do in the destructor "delete single" it produces an infinite
loop.
How could I free the memory associated to the variable single?
Thank you.
class Singleton
{
private:
static bool instanceFlag;
static Singleton *single;
Singleton()
{
//private constructor
}
public:
static Singleton* getInstance();
void method();
~Singleton()
{
instanceFlag = false;
}
};
bool Singleton::instanceFlag = false;
Singleton* Singleton::single = NULL;
Singleton* Singleton::getInstance()
{
if(! instanceFlag)
{
single = new Singleton();
instanceFlag = true;
return single;
}
else
{
return single;
}
}
void Singleton::method()
{
cout << "Method of the singleton class" << endl;
}
int main()
{
Singleton *sc1;
sc1 = Singleton::getInstance();
sc1->method();
return 0;
}
|