When could std::priority_queue::pop throw an exception

我怕爱的太早我们不能终老 提交于 2020-01-14 12:44:49

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!