pop()
indeed destroys the first element.
Note however that in the first case the std::queue
is of naked pointers and destroying a naked pointer doesn't do anything to the pointed-to object.
In the second case the std::queue
contains object copies so when calling pop()
the first copy will be destroyed and removed.
In the first case unless someone else knows the address of the object pointed to by the destroyed pointer and calls delete
on that address, the object will be "leaked" (i.e. just forgotten about): its destructor will never be called and the memory it is using will never be reclaimed and reused for something else.
To destroy the pointed-to object in the first case the normal procedure is
delete queue.front();
queue.pop();
If instead of "naked" pointer you use "smart" pointers then the "leak" problem will go away in most cases(*). Note that it doesn't mean the destructor of the pointed-to object will be called in pop()
, but that it will called at the appropriate time when no one else knows the address of the pointed-to object (if everything is done correctly when manipulating the smart pointers).
(*) If your data model is complex and you have std::shared_ptr
networks of objects pointing to each other then there is a risk of creating "reference loops". In this case std::shared_ptr
even if used correctly is not enough to prevent leaking of loops (e.g. leaking a cople of objects A
and B
where each one has a std::shared_ptr
to the other) and a true garbage collector is needed. Unfortunately C++ doesn't provide this kind of machinery in the standard library.