[Bug libstdc++/55841] Unexpected behavior from STL's queue

redi at gcc dot gnu.org gcc-bugzilla@gcc.gnu.org
Tue Jan 1 21:16:00 GMT 2013


http://gcc.gnu.org/bugzilla/show_bug.cgi?id=55841

Jonathan Wakely <redi at gcc dot gnu.org> changed:

           What    |Removed                     |Added
----------------------------------------------------------------------------
             Status|UNCONFIRMED                 |RESOLVED
         Resolution|                            |INVALID

--- Comment #2 from Jonathan Wakely <redi at gcc dot gnu.org> 2013-01-01 21:16:16 UTC ---
N.B. std::queue is a very thin adaptor (i.e. wrapper) around another container,
the behaviour you are reporting is actually the behaviour of std::deque, not
std::queue.


(In reply to comment #0)
> Apparently, when a std::queue is empty, front() returns some bizarre output

Assuming you're using std::deque as the queue's container_type, it is undefined
behaviour to call front() when it is empty, so any result is allowed.

> Why doesn't front() throw an exception when there's no element?

It would be slower to check it on every use.  If I push one hundred elements
into the container then call pop() one hundred times there would be one hundred
useless checks that I don't want.

If you are not sure if it's safe to call pop() in your program then you should
do the check in your own code, not force all users to pay for the checking on
every call in every program.

> And why does pop() break the queue?

Because calling pop() on an empty sequence is undefined behaviour.

> If I understand correctly, the standard doesn't define what to do in this case
> (I don't understand why), but even so, libstdc++ can do something sensible in
> this case...

As Chris said, use the debug mode.

Or write your own wrapper around std::deque that adds checking and then use
that as the container_type for std::queue.

> Sure, I can always check empty() before calling front() or pop(), but isn't
> that very anti-C++-like, as exceptions were invented exactly so that code
> doesn't need to be littered with sanity checks like this, and rare cases of
> insanity cause exceptions?

No, it's more C++-like to not pay for features you don't use. If I don't need
to check the size on every call I shouldn't have to pay for that check.  If you
need to check it you should pay for the checking, by adding it yourself.



More information about the Gcc-bugs mailing list