By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
446,421 Members | 1,053 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 446,421 IT Pros & Developers. It's quick & easy.

Deleting pointers from deque

P: n/a
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)

Jul 23 '05 #1
Share this Question
Share on Google+
1 Reply


P: n/a
<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.

Jul 23 '05 #2

This discussion thread is closed

Replies have been disabled for this discussion.