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
Online sources are worth what you pay for them - get a proper reference like Josuttis's book. pop() does not "call the destructor" - it simply removes an element from the queue adaptor's underlying representation (by default a std::deque) by calling pop_front() on it. If the thing being popped has a destructor, it will be used when the popped object goes out of scope, but the queue class has nothing to do with it.
Pointers themselves don't actually have destructors, so calling pop()
on a queue containing a pointer won't call the destructor of the object your pointer points to.
"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.