什么时候std :: priority_queue :: pop会引发异常 [英] When could std::priority_queue::pop throw an exception

查看:203
本文介绍了什么时候std :: priority_queue :: pop会引发异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

std::priority_queue pop() 方法不是声明为noexcept,因此理论上可能会引发异常.但是它什么时候会引发异常,这些异常又会是什么呢?

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?

推荐答案

可以标记为nothrow,但不能标记为

It could be marked nothrow, but isn't.

void pop();

从优先级队列中删除顶部的元素.有效呼叫

Removes the top element from the priority queue. Effectively calls

std::pop_heap(c.begin(), c.end(), comp); c.pop_back();

c默认为std::vector.

[vector.modifiers]/4&5

void pop_back();

4/复杂度:T的析构函数的调用次数等于擦除的元素数,而 T的赋值运算符的调用次数等于向量中被删除元素之后的元素数量 .

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 :除非T的赋值运算符或移动赋值运算符抛出异常,否则什么都不会发生.

5/ Throws: Nothing unless an exception is thrown by the assignment operator or move assignment operator of T.

* 因此,仅调用T的析构函数,并且由于

*So only the destructor of T is called and that one cannot throw because of

[requirements.on.functions]/2.4

2/特别是在以下情况下效果不确定:
[...]
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.

为什么std::priority_queue::pop不是nothrow?

由于从T::~T引发的异常将导致UB,因此实现可以假定它不会发生并且仍然符合标准.处理它的另一种方法是让此类库函数nothrow(false)而不处理它.

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.

这篇关于什么时候std :: priority_queue :: pop会引发异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆