gpt4 book ai didi

c++ - std::accumulate 可以抛出吗?

转载 作者:行者123 更新时间:2023-12-02 09:56:43 25 4
gpt4 key购买 nike

std::accumulate 的 C++ 引用没有提到 std::accumulate 可能抛出的任何异常,仍然它的定义不包含 noexcept。假设一个人使用不抛出的类型和操作,在声明为 noexcept 的成员函数中使用 std::accumulate 是安全的,还是在 UB 中发生?

例如:

#include <iostream>
#include <numeric>
#include <vector>

class A {
std::vector<int> m_v;
public:
A(std::size_t N) : m_v(N, 1) { }
int sum() const noexcept { return std::accumulate(m_v.begin(), m_v.end(), 0); }
};

int main()
{
A x{3};
std::cout << x.sum() << std::endl;
return 0;
}

是否将 A::sum() 声明为 noexcept UB 的来源?

最佳答案

std::accumulate() 有先决条件,例如,范围的末尾可以从范围的开头到达。到目前为止,标准库还没有将 noexcept 放在有前提条件的函数上(至少,一般情况下没有;可能有特殊情况),因为调试实现可以​​断言存在问题,例如,通过抛出异常:当未定义的行为被触发时会发生什么是未定义的,如果他们愿意的话,实现可以自由定义任何一个。

此外,std::accumulate() 调用的任何函数都允许抛出异常,即任何 noexcept 声明都需要是有条件的。我认为算法一般不太可能获得相应的 noexcept 声明。

由于规范未提及在合约内调用时 std::accumulate() 抛出的任何情况,因此如果调用的操作均未抛出,则不会抛出。

关于c++ - std::accumulate 可以抛出吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59493624/

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