Re: Passing Pointers -- where to delete them
On Mar 3, 6:37 am, Arv <arvind.b...@gmail.com> wrote:
[...]
I now realise how much thinking I should do before creating
objects on the heap.
I'd argue that you should do a lot of thinking before creating
objects anywhere:-). My own experience is that programming is
about 60% design, 30% coding, and 10% debugging. I've seen
people who inverse those percentages, with 10% design and 60%
debugging, but they tend to take a lot more time to get working
code, and the results are rarely as reliable as what I (and
others I know with similar percentages) deliver.
I was originally thinking that people use heap so that stack
doesn't get bloated with memory.
That occasionally happens as well, although most of the time, in
such cases, the allocations will be hidden in standard classes,
like std::vector. If you do have a single object where sizeof(
MyType ) is a couple of megabytes, you might end up having to
allocate it dynamically, rather than on the heap, but most
applications probably shouldn't have this sort of object to
begin with.
That is why I was thinking sometimes ppl use new in places
where it can be created on the stack...
I got most things clarified now, but I still have a doubt
related to shared_ptr. When I use a singleton object, would a
shared_ptr help?
I don't think so. The whole point of a singleton is that it has
"static" lifetime, so no one using it should destruct it.
Because when I use new inside the singleton's getInstance
method, I am not sure when to delete it, since it is a static
member, i am not sure putting the delete in the destructor
would help. Should I have another method called resetInstance
or something?
There are two idioms, according to what is needed. Most of the
time, it's probably preferable to never destruct the singleton
object---it disappears when the program does, after all of the
destructors of static objects have been called. In such cases,
getInstance() (or just instance()---conceptually, this function
represents the object, and not an action, so it is probably more
appropriate to name it with a noun) allocates, and no one ever
deletes. The instance() function looks something like:
Singleton&
Singleton::instance()
{
static Singleton* theOneAndOnly = new Singleton ;
return *theOneAndOnly ;
}
In the occasional cases where a delete is necessary (or doesn't
hurt), the usual solution is to use a local static:
Singleton&
Singleton::instance()
{
static Singleton theOneAndOnly ;
return theOneAndOnly ;
}
(You'll often see somewhat more complicated versions, for
example, when thread safety is an issue. You probably shouldn't
worry about them for the moment.)
--
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