Singleton destruction

D

Dave

Hello all,

I have made a class into a singleton by having a static get() method which
returns a pointer to the one-and-only instance. This method creates the
instance on the heap if it hasn't already done so in a prior call.
Constructors are private so that the class may not be instaniated from
outside. As I understand it, this is the standard approach and is nothing
new.

I have no need to ever destroy this singleton and re-create a new one in
it's place, so I have not provided a method for destruction.

My question is: Where in my code, if ever, should the singleton be
deallocated? Is it standard practice to just ignore this memory, or would
it really be more proper to find some way to deallocate it manually upon
app. exit?

Thanks,
Dave
 
J

John Harrison

Dave said:
Hello all,

I have made a class into a singleton by having a static get() method which
returns a pointer to the one-and-only instance. This method creates the
instance on the heap if it hasn't already done so in a prior call.
Constructors are private so that the class may not be instaniated from
outside. As I understand it, this is the standard approach and is nothing
new.

There is another approach, declare the object as static within the get
method. This ensures that it will be destructed on exit.

class X
{
static X& get()
{
static X the_x;
return the_x;
}
};
I have no need to ever destroy this singleton and re-create a new one in
it's place, so I have not provided a method for destruction.

My question is: Where in my code, if ever, should the singleton be
deallocated? Is it standard practice to just ignore this memory, or would
it really be more proper to find some way to deallocate it manually upon
app. exit?

Depends on how good your OS is on reclaiming resources from exited
applications. I don't think operating systems have much problem with memory,
that will automatically be reclaimed. Other resources, well I think you have
to consult your documentation.

The best discussion I know of singletons and the policies you can adopt for
them is in Andrei Alexandrescu's book Modern C++ Design. You can get the
code if not the book online, google for loki library.

john
 
D

David Harmon

On Thu, 8 Apr 2004 19:30:52 +0100 in comp.lang.c++, "John Harrison"
There is another approach, declare the object as static within the get
method. This ensures that it will be destructed on exit.

And if something requires that the object be allocated with new, that's
a case where a static std::auto_ptr<t> can do the job.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,009
Latest member
GidgetGamb

Latest Threads

Top