Deleting pointers from deque

Discussion in 'C++' started by mm, Apr 1, 2005.

  1. mm

    mm Guest

    Hi All,

    I have a deque which holds pointers to type user defined struct uwb_t.

    //The deque and the pointer to struct is declared as follows

    #include <deque.h>

    void process1()
    {
    deque <struct uwb_t*> uwb_header_q;
    struct uwb_t* header_uwb;
    .......

    //process1 goes on to assign the pointers and pushes them onto the deque:

    header_uwb = new (struct uwb_t);
    uwb_header_q.push_back(header_uwb); // Push the pointer onto the deque
    }

    // Another process deals with the header at the front of the queue.
    // Once processing is complete, I want to delete the ptr and free the
    sizeof(uwb_t) memory that was allocated via the new operator
    // Is this the correct way to do it?
    void process2()
    {
    ............ // process head of queue
    delete uwb_header_q[0]; // Free the memory occupied by the
    object pointed to by the head of the deque
    uwb_header_q.pop_front(); // Remove the pointer from the head of the
    deque
    }


    Thanks!
    -Martin (apologies for duplicate on c++.moderated)
    mm, Apr 1, 2005
    #1
    1. Advertising

  2. mm

    Guest

    <snip>
    > // Another process deals with the header at the front of the queue.
    > // Once processing is complete, I want to delete the ptr and free the
    > sizeof(uwb_t) memory that was allocated via the new operator
    > // Is this the correct way to do it?
    > void process2()
    > {
    > ........... // process head of

    queue
    > delete uwb_header_q[0]; // Free the memory occupied by

    the
    > object pointed to by the head of the deque
    > uwb_header_q.pop_front(); // Remove the pointer from the head

    of the
    > deque
    > }


    This works BUT it's dangerous to use pointers in the way with the STL
    containers. It's safer to encapsulate the pointer in an object and let
    the object take care of memory freeing (and possibly reference
    counting). A number of good smartpointers can be found in the boost
    library (www.boost.org). My suggestion is using the boost::shared_ptr.
    , Apr 1, 2005
    #2
    1. Advertising

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

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Xamalek
    Replies:
    7
    Views:
    685
  2. Russell Warren
    Replies:
    5
    Views:
    416
    Tim Peters
    May 2, 2006
  3. Harry Barker
    Replies:
    2
    Views:
    512
    Alf P. Steinbach
    Apr 19, 2006
  4. cerr

    pointers, pointers, pointers...

    cerr, Apr 7, 2011, in forum: C Programming
    Replies:
    12
    Views:
    667
  5. crea
    Replies:
    2
    Views:
    406
    Nobody
    Dec 28, 2012
Loading...

Share This Page