问题
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?
回答1:
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
.
[vector.modifiers]/4&5
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.
来源:https://stackoverflow.com/questions/50740081/when-could-stdpriority-queuepop-throw-an-exception