Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ std::queue::pop() calls destructor. What of pointer types?

Tags:

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 stores pointer types.

For the pointer type, I'm having trouble deleting the elements of the queue on destruction. The reason is that I don't know a way to remove the items from the queue safely.

This reference states (vacuously, so I guess it doesn't actually STATE it) that the only way to remove elements from the queue is to call pop(). The reference also says that pop() calls the destructor for the item.

Well, this causes problems with my pointer types because they may or may not actually point to aggregates. If one of them points to an aggregate, they all will, but because the wrapper is templated, there is no guarantee which type (aggregated or non-aggregated) we are dealing with.

So, when pop() calls the destructor, what happens? How do I ensure that everything is being removed and the memory deallocation properly?

Lastly, my solution is using an older version of GCC for ARM9. I don't have control over this. I understand that there are libraries that have smart pointers and containers that would assist here, but they are off-limits for me.

like image 459
San Jacinto Avatar asked Jan 04 '10 21:01

San Jacinto


People also ask

Does queue pop call destructor?

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.

What does the destructor for pointers do?

It destroys the object that's pointed to (using its destructor, if it has one, and doing nothing otherwise), and deallocates the memory that's pointed to.

Do smart pointers call destructor?

The smart pointer destructor contains the call to delete, and because the smart pointer is declared on the stack, its destructor is invoked when the smart pointer goes out of scope, even if an exception is thrown somewhere further up the stack.

Does deleting a pointer call the destructor?

Default destructors call destructors of member objects, but do NOT delete pointers to objects. Thus, we need to write destructors that explicitly call delete.


1 Answers

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.

like image 133
Greg Hewgill Avatar answered Sep 18 '22 15:09

Greg Hewgill