Hello there. I have been working on a Singleton class based off a sample code on a website which I can't remember (sorry for the author). I tried to test the class in a separate project and found that this little example works (i.e. displays twice the message) whereas I expect it to crash or at least output garbage on the 2nd time. Any idea why ?
Code:
//
// system.h
//
#ifndef SINGLETON_H
#define SINGLETON_H
#include <iostream>
//****************************
// Singleton class declaration
//****************************
template <typename T>
class Singleton {
private:
static T* Instance;
protected:
Singleton<T> () { }
public:
static T* Create() {
if(Instance == 0) {
Instance = new T;
}
return Instance;
}
static void Destroy() {
if(Instance != 0) {
delete Instance;
Instance = 0;
}
}
};
template <typename T>
T* Singleton<T>::Instance = 0;
class Child : public Singleton<Child> {
public:
void Whatever() { std::cout << "Inherited"; }
};
#endif // SINGLETON_H
Code:
#include "singleton.h"
int main(int argc, char** argv) {
Child* instance = Singleton<Child>::Create();
instance->Whatever();
Child::Destroy();
instance->Whatever();
return 0;
}
I expect that after the call to Destroy() the memory will be deallocated and the pointer set to 0 but this does not seem to happen :/