[Cs3] std::queue::pop

Mikhail Nesterenko mikhail at cs.kent.edu
Tue Apr 7 13:15:25 EDT 2020


> 
> I'm working on lab 10 part 3 and am wondering if you know if there is a
> reason that std::queue::pop doesn't return the item it has 'popped' off the
> queue. In order to push the item from the front of a queue to the back I
> have to do the following:
> 
> readyQ.push(readyQ.front());
> readyQ.pop(); // pop doesn't return the value removed for some reason
> 
> Which is odd to me as my first thought (especially after learning the STL
> as we have) is to do the following
> 
> readyQ.push(readyQ.pop());

pop() does not return the element popped in queue or stack or
priority_queue in STL. Two major reasons:

- efficiency: the returned item has to be copied - pop() cannot return 
  a reference since this element is no longer in the container

- (thread) safety: if the copy constructor throws an exception and
  refuses to create a copy, the element is already removed from the
  queue
  
So STL is stuck with a bit counter-intuitive idiom: first do first()
(or top() in case of stack), then pop().

See more detailed discussion here:

https://stackoverflow.com/questions/25035691/why-doesnt-stdqueuepop-return-value

Thanks,
--
Mikhail


More information about the cs3 mailing list