Re: Does deleting a container of pointers also delete the (contained) pointers?

From: Cy Edmunds (cedmunds_at_spamless.rochester.rr.com)
Date: 11/04/03


Date: Tue, 04 Nov 2003 02:29:17 GMT


"Xamalek" <xamalek-nospam-spammm@yahoo.com> wrote in message
news:hgBpb.13325$Vg7.6043@newssvr14.news.prodigy.com...
> Greetings,
>
> I have a question. When using an STL container, does deleting a container
of
> pointers also call delete on the (contained) pointers?

No. Imagine if it did:

void disaster()
{
    std::vector<int*> v;
    int k;
    v.push_back(&k);
} // undefined behavior here if std::vector deleted contained pointers

There is no way for the collection to tell if the pointer was obtained from
the new() operator or not.

>
> For example, if I have (ignore the fluff, it is simply used to explain my
> issue)
>
> struct Proc
> {
> int uid;
> int pid;
> int parent_id;
> };
>
> and then I have
>
> queue<Proc*> Q = new queue<Proc*>;

Huh? I think you mean:

queue<Proc*> *Q = new queue<Proc*>;

although why you would dynamically allocate it is beyond me.

>
> // I then populate the queue with Proc types
>
>
> If I do a
>
> delete Q;
>
> will that destroy the queue and the inner elements as well, or do I have
to
> do the work of ensuring that delete is also called on all the Proc*'s
> (contained by the queue) as well?

You have to delete them yourself unless you use a reference counted smart
pointer.

>
> Sincerely,
> X
>
>

-- 
Cy
http://home.rochester.rr.com/cyhome/


Relevant Pages

  • Re: Allocating space for array of pointers?
    ... But how do I allocate space for these pointers? ... for a container object and make cppoint to it, ...
    (comp.lang.c)
  • Re: Allocating space for array of pointers?
    ... But how do I allocate space for these pointers? ... for a container object and make cppoint to it, ...
    (comp.lang.c)
  • Re: inheritance from STL-container
    ... First of all, you've shown the DBC ... number of algorithms are implemented as member functions. ... container wouldn't allow you to add the DBC stuff to them anyway. ... Generally smart pointers. ...
    (microsoft.public.vc.stl)
  • Re: Strategies for avoiding new?
    ... >allocate and store in a container" strategy. ... So whether you store pointers or values in the container depends upon what ...
    (alt.comp.lang.learn.c-cpp)
  • Re: Strategies for avoiding new?
    ... > container is important (which is why I use map or whatever.) ... from the container and manipulate it directly. ... So after my snippet, ... using pointers is unnecessary. ...
    (alt.comp.lang.learn.c-cpp)