Group: comp.lang.c++
From: Ron Eggler
Date: Thursday, April 10, 2008 6:31 PM
Subject: Re: destroy singleton?

Christopher wrote:

> On Apr 10, 5:09 pm, Ron Eggler wrote:
>> Hi,
>>
>> I created a singleton class and can't get rid of it anymore ;)
>> Uhm, the important things in the definition look like that:
>> [header]
>> class GPIOcontrol: public TSPThread
>> {
>> public:
>> static GPIOcontrol* instance(GPSData*); //Method returns pointer
>> of
>> singleton instance of this class
>> ~GPIOcontrol();
>> static GPIOcontrol* pinstance; //The
>> instance pointer that is returned
>> by the method instance() - this is a singleton class
>>
>> protected:
>> GPIOcontrol(GPSData *gpsDataObj);
>>
>> private:
>>
>> };
>>
>> void PrepareToDie(void); //This
>> method unsets the singleton pointer
>> [/header]
>> I call the PrepareToDie() function from the destructor and get a
>> segmentation fault, the implementation of this function looks like:
>> [implementation]
>> void PrepareToDie(void) //This
>> method unsets the singleton pointer
>> {
>> delete GPIOcontrol::pinstance;
>> }
>> [/implementation]
>> I first had thsi delete PrepareToDie function as a public method in the
>> class what returned me a seg. fault so i thought i could resolve it by
>> moving it out of the class but it apparently wouldn't work.
>> Does anyone know how i can get rid of it and free its memory?
>>
>> Thank you for hints & suggestions!
>> Ron
>> --
>> weeks of software enineering safe hours of planing ;)
>
>
> If its a singleton, then it should not be deleted until program exit.

It is at the program exit where i want to delete it.

> There are many singleton patterns, one of which uses a reference
> instead of a pointer, in order to rely on the program exit to release
> it. I'd look over some of those. Also keep in mind the problems with
> singletons and be sure you are handling them or IMO avoiding using
> singletons to avoid the problems!

Will keep in mind for future designs....

> Google "static initialization fiasco"
> Read up on global and static deallocation at program exit time, and
> note the order is undefined! This caused a slew of bugs in the code
> I've seen in the past.

Oh wow, haven't heard of that but shouldn't be applicable in my application
>
> IMHO it is better to avoid them altogether and create an instance of
> the class at program start-up and then pass references to it around
> instead. that way you can control init and release order. Especially
> when it is obvious that one global,static (singleton) depends on
> another.
>
> Anyway, the obvious ism, your pointer is probably null by the time the
> destructor gets called.

negative, it isn't. :(

--
weeks of software engineering safe hours of planning ;)

Safety Articles | Usenet Groups | 20lbs in 30 days