Re: destroy singleton?
On Apr 11, 12:09 am, Ron Eggler <t...@example.com> wrote:
I created a singleton class and can't get rid of it anymore ;)
That's usually a feature, not a bug, where singletons are
concerned. In general, I avoid ever deleting a singleton.
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:
=46rom the destructor of what?
[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?
Most of the time, it is preferable not to delete the singleton,
ever. That way, it remains accessible even in destructors of
static objects. In the rare cases where deletion is necessary,
the usual solution I've seen is to use a local static:
GPIOcontrol*
GPIOcontrol::instance()
{
static GPIOcontrol theOneAndOnly ;
return theOneAndOnly ;
}
In this case, the compiler takes care of ensuring that the
object is only created once, and that the destructor is called
once during program shutdown.
(Note that this will only work in a multithreaded environment if
you can ensure that instance is called at least once before
threads are started, or that it is only called from a single
thread. Otherwise, you need a scoped lock before the static.)
--
James Kanze (GABI Software) email:james.kanze@gmail.com
Conseils en informatique orient=E9e objet/
Beratung in objektorientierter Datenverarbeitung
9 place S=E9mard, 78210 St.-Cyr-l'=C9cole, France, +33 (0)1 30 23 00 34