Deleting pointers from deque

M

mm

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)
 
V

velthuijsen

// 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.
 

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,769
Messages
2,569,581
Members
45,056
Latest member
GlycogenSupporthealth

Latest Threads

Top