gpt4 book ai didi

c++ - std::priority_queue::pop 什么时候可以抛出异常

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:41:56 25 4
gpt4 key购买 nike

pop() std::priority_queue 的方法未声明为 noexcept,因此理论上可以抛出异常。但它什么时候会抛出异常,这些异常可能是什么?

最佳答案

它可以被标记为nothrow,但不是。

为什么 std::priority_queue::pop 可以* 不抛出

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/ 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.

*所以只有 T 的析构函数被调用并且不能抛出因为

[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.

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

由于从 T::~T 抛出的异常会导致 UB,实现可以假设它不会发生并且仍然符合标准。另一种处理方法是让这样的库函数nothrow(false)而不处理它。

关于c++ - std::priority_queue::pop 什么时候可以抛出异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50740081/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com