I have a std::queue
that is wrapped as a templated class to make a thread-safe queue. I have two versions of this class: one that stores value types, one that s
"How do I ensure that everything is being removed and the memory deallocation properly?"
If you absolutely have to store pointers in your queue, and you want them to be automatically freed when they're pop
ed, then instead of a queue of pointers, you need a queue of objects which store a pointer, and delete it in their destructor. You could for example use a queue of shared_ptr. shared_ptr isn't in the standard library, but it's part of TR1 and is widely available.
Otherwise, it's the responsibility of the caller to delete the object:
T *off = q.front();
q.pop();
delete off;
The summary is that containers of pointers to dynamically allocated objects are a bit awkward. If you can design your program so that containers store copies of your objects, instead of pointers to dynamic objects, then do so. Failing that, you're responsible for resource ownership, not the container. STL containers know nothing about ownership, they just copy and destroy their value_type
. Copying and destroying pointers does nothing to the objects they point to.