Aufruf von exit(
) in Singleton Destruktor verursacht eine Endlosschleife, das passiert nur mit der Singleton-Klasse und es funktioniert gut woanders! Dies ist der Code:Warum ruft exit() in Singletons Destruktor eine Endlosschleife auf?
#include <iostream>
#include <stdlib.h>
class Singleton{
private :
Singleton(){}
public : // public destructor , allow 'delete' or whatever , not our subject
~Singleton()
{
std::cout<<"~Singleton()"<<std::endl;
exit(0);
}
static Singleton * GetInstance()
{
static Singleton s;
return &s;
}
};
int main()
{
// Signleton s; , this is safe when the constructor is public
Singleton::GetInstance(); // this enter an infinate loop
return 0;
}
Ausgang:
~Singleton()
~Singleton()
~Singleton()
~Singleton()
~Singleton()
~Singleton()
~Singleton()
~Singleton()
~Singleton()
~Singleton()
~Singleton()
~Singleton()
~Singleton()
~Singleton()
~Singleton()
~Singleton()
~Singleton()
~Singleton()
~Singleton()
....
Beachten Sie, dass gcc nicht in der Endlosschleife abtaucht http://coliru.stacked-crooked.com/a/585f9ef22160ed67 –