Reputation: 97
I am working on a question involving lots of queues and got curious that in order to free the memory of an unused queue, is emptying the queue(popping) enough or do I have to do something else ?
Tried using 'free' , but got error.
Upvotes: 0
Views: 780
Reputation: 69
Popping should be enough as STL classes manage their own resources, e.g.
queue <int> g;
g.push(10);
g.push(20);
g.push(30);
while (!g.empty())
{
g.pop();
}
Upvotes: 1
Reputation: 3292
std::queue is just a wrapper around other STL container types, by default std::deque, but also possibly std::list or std::vector. When your queue gets out of scope, the destructor of the underlying container is automatically triggered.
If you want to manually deallocate the memory consumed by a queue, and the data type of your queue is either a primitive (int, float, ...) or has a proper destructor (most if not all STL data types), you can do in C++11 and later:
std::queue<your_type>().swap(your_queue);
or for older versions:
{
std::queue<your_type> temp;
std::swap(temp, your_queue);
}
It makes an empty queue, swaps its contents with your queue, and destroys it (because it gets out of scope right after the swap), leaving only the empty one in your hand.
If you are using a queue of a custom type that doesn't have a proper destructor, I think the only way is to pop out the elements one by one and manually deallocating the memory of the popped element.
Upvotes: 2