Archived

This topic is now archived and is closed to further replies.

johnnyBravo

Possibly for singleton class to delete its reference?

Recommended Posts

Hi, Ive got a singleton class, I don''t like leaving my reference undeleted. So is the code at the bottom an ok way of deleteing it? And would i still bother deleting the class declarration eg. MyClass single; single = MyClass::getInstance(); delete single; Do i call the delete single? Is that right? i havent got the code with me but its something like this:
class MyClass {
private:
    MyClass(){}
    ~MyClass()
    {
        delete reference;
    }
    static MyClass reference;
public:
    MyClass getInstance()
    {
        if (referene!=NULL)
            reference = new MyClass();
     }
};
thanks,

Share this post


Link to post
Share on other sites
my singleton works something like this

Class1 *C = Class1::getInstance();
and
C = Class1::destroyInstance(); // returns null
or
Class1::destroyInstance(); directly

one problem with your way would be if you dont have the class reference at hand the code would look strange (but still work):

delete MyClass::getInstance();

It looks bad because nowhere do you call new MyClass... (inside the singleton, but not in the code using the singleton)

Also, I use the atexit hack, to always make sure that all my singletons is deleted before the program exits...

Share this post


Link to post
Share on other sites
johny,

your method does not make sense. The destructor will only be called when delete is called on an instance, or when a statically allocated instance goes out of scope. In other words, your singleton will never be destroyed, and if somehow it were, it would cause an infinite recursion.

Deleting singletons is a tricky subject. The most straightforward approach may well be to have a static destroyInstance() method, as Nine said.


"Sneftel is correct, if rather vulgar." --Flarelocke

Share this post


Link to post
Share on other sites