Re: Passing Pointers -- where to delete them
On Mar 2, 7:34 pm, "jason.cipri...@gmail.com"
<jason.cipri...@gmail.com> wrote:
On Mar 2, 6:30 pm, James Kanze <james.ka...@gmail.com> wrote:
[snip]
If you can do this, why use dynamic allocation?
[snip similar questions]
I am not arguing for preferring dynamic allocation over other methods.
I'm just stating that there are plenty of situations when there is no
other way, or when other ways just become cumbersome.
You are right, most of the examples I gave were too contrived to
warrant use of 'new'. I would definitely not recommend using 'new' in
a context like this if you can avoid it:
{
Object *o = new Object();
{
Object *p = new Object();
delete p;
}
delete o;
}
You should not be using new like that. I once knew a guy who used to
write code like this:
{
int *a = new int;
int *b = new int;
// some arbitrary operations
*a = 3;
*b = *a * 2;
printf("%i", *b);
delete b;
delete a;
}
I have no idea why he did that. From what I understood he came from
some other programming language background where that somehow made
sense to him. DO NOT DO THAT! That is a great example of when NOT to
use new.
On the other hand, for a more complex application or situation where
dynamically allocating memory is the only good way to do it, I see no
problem when using new.
I don't have the time to invent and code entire applications for the
purposes of example on a newsgroup, though, so contrived examples are
going to have to be good enough.
P.S. Another example of when you would want to use 'new' is when you
are using placement new to construct objects in your own memory pool.
There is no other way to construct objects at a given location.