i have the code as below :
class Singleton {
private:
int i;
static bool stnflag;
static Singleton* single;
Singleton(int a)
{
i=a;
}
public:
static Singleton* getinstance(int);
void function();
~Singleton()
{
cout << "destructor is being called" << endl;
stnflag=false;
}
};
bool Singleton::stnflag=false;
Singleton* Singleton::single=NULL;
Singleton* Singleton::getinstance(int a)
{
if(!stnflag)
{
single = new Singleton(a);
stnflag=true;
return single;
}
else
{
cout << "already single object created" << endl;
return single;
}
}
void Singleton::function()
{
cout << "private member value in single ton class is :" << i << endl;
}
int main()
{
Singleton *s1,*s2;
s1=Singleton::getinstance(3);
s1->function();
s2=Singleton::getinstance(4);
s2->function();
delete s1;
delete s2;
return 0;
}
when delete s2 is called the destructor is called second time also!!but how it is possible? already the pointer of the object is deleted at delete s1 ri8..but i’m getting the print statement in the destructor for second delete s2 too..can anybody giveme the reason..but as per my assumption it shud through an error of double free pointer ri8!!
Well, don’t call
deleteon it twice!Calling
deleteon an already deleted object is undefined behaviour, not a guaranteed crash.You should consider having
getinstance()return a reference, rather than a pointer.