user3712853
user3712853

Reputation:

Deallocating from C++ priority_queue

Is it safe to delete an element in a std::priority_queue and pop it afterwards or does the pop try to do anything with the reference other than discarding it?

  while(!priority_queue.empty()){
    delete priority_queue.top();
    priority_queue.pop();
  }

Upvotes: 0

Views: 486

Answers (2)

Gem Taylor
Gem Taylor

Reputation: 5613

So this page is useful: http://www.cplusplus.com/reference/queue/priority_queue/pop/

What it says is that the objects in the queue are destructed.

However if the object doesn't actually have a destructor that deletes its content then you have to delete the content yourself. But that is not OO programming, it is just lazy use of a container.

Note that say a pair of objects that both do have proper destructors will call both destructors correctly.

So in general, no, you shouldn't be deleting the objects explicitly, but is you have lazily written a container of raw pointers, or pairs of pointers, then you will have to, because you wont benefit from destructor calling.

Upvotes: 1

Hatted Rooster
Hatted Rooster

Reputation: 36483

After clarification from OP saying that the queue doesn't container any pointers, just objects :

You don't have to call delete at all. Just call pop() only in your while loop. The container deals with deallocation.

Upvotes: 3

Related Questions