I have a singleton class, whose instance get initialized at global scope within the class's CPP file:
Singleton* Singleton::uniqueInstance = new Singleton();
Its header file looks like:
class Singleton {
public:
static Singleton& getInstance() { return *uniqueInstance; }
static bool destroyInstance() { delete uniqueInstance; }
private:
//...
//... typical singleton stuff
static Singleton* uniqueInstance;
}; // end of class Singleton
I noticed that its destructor dodn't get executed during program termination, thus I added a public static interface Singleton::destroyInstance(), to be manually invoke by client code before the program exits, for instance deletion. This snippet is not the complete code, and assumed that there are other codes that dealing with thread safety issue. In this case, how can I make use of RAII to eliminate the need of introducing such an interface? Thanks for advice.
Singleton are easy to create, unless you are in a MultiThreaded environment. If you can, you'll want to make sure that only one thread is trying to create your singleton (and thus destroy it). Once created it may be used by multiple threads at once... though that may not be the best way to deal with this.
Anyway, a very simplistic option is thus:
class MySingleton
{
public:
static MySingleton& Intance() { static MySingleton M_Instance; return M_Instance; }
private:
MySingleton() {}
};
It works well as long as you're not using MI and you do not use the singleton during globals destructions. Also it does not work with VC2003 at least (used to instantiate one singleton for each library the method was called....), I don't know with more recent versions, we've stopped compiling on windows altogether a while ago.
Now, if you want to really learn more about Singleton:
Alexandrescu concentrated on this for a full chapter in Modern C++ Design, if you don't have access to the book you can still read the code that resulted from the reflexion in Loki.
Also, you might simply use alternative approaches to the design. Singleton may make testing difficult, there have been interesting thoughts about this from the people that support Dependency Injection. Take a peek at Misko Hevery blog entry.
The destructor won't be called automatically because the global object is a pointer, not the object itself. If you were to declare the global object like this:
Singleton Singleton::uniqueInstance();
then the destructor would be automatically called. However, you wouldn't be able to control exactly when the constructor and destructor are called (in relation to construction and destruction of other global objects). If this isn't important to you, then you can use the above method.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With