The pop()
method of std::priority_queue
is not declared noexcept
, so in theory could throw an exception. But when might it throw an exception, and what might those exceptions be?
-
interesting question. `pop_heap` is not nothrow either. – Richard Hodges Jun 07 '18 at 11:35
-
1Most functions that exhibit UB are not marked `noexcept` so that implementations can throw exceptions if they want. – Rakete1111 Jun 07 '18 at 11:37
-
See also https://stackoverflow.com/questions/2852140/priority-queue-clear-method. – Raedwald Jun 07 '18 at 14:08
1 Answers
It could be marked nothrow
, but isn't.
Why std::priority_queue::pop
could* not throw
void pop();
Removes the top element from the priority queue. Effectively calls
std::pop_heap(c.begin(), c.end(), comp); c.pop_back();
c
is by default an std::vector
.
void pop_back();
4/ Complexity: The destructor of T is called the number of times equal to the number of the elements erased, but the assignment operator of T is called the number of times equal to the number of elements in the vector after the erased elements.
5/ Throws: Nothing unless an exception is thrown by the assignment operator or move assignment operator of T.
*So only the destructor of T
is called and that one cannot throw because of
[requirements.on.functions]/2.4
2/ In particular, the effects are undefined in the following cases:
[...]
2.4/ if any replacement function or handler function or destructor operation exits via an exception, unless specifically allowed in the applicable Required behavior: paragraph.
Why is std::priority_queue::pop
not nothrow
?
Since an exception thrown from T::~T
would lead to UB, the implementation can assume it cannot happen and still conform to the Standard. Another way to deal with it is to let such library functions nothrow(false)
and not dealing with it.

- 38,212
- 9
- 96
- 149
-
1`erase` and `pop_back` share the description, but it clearly states that "the assignment operator of T is called the number of times equal to the number of elements in the vector after the erased elements". In case of `pop_back` there are no elements after the erased element, so it should not throw. – Jun 07 '18 at 11:58