【问题标题】:Is it exception-safe that return the right value which is return of function in c++?在 c++ 中返回正确的值是否是异常安全的?
【发布时间】:2021-07-18 13:01:48
【问题描述】:

在 c++ 中返回正确的值是否是异常安全的? 例如,

template<typename Iterator, typename T>
T my_accumulate(Iterator first, Iterator last) {
    return std::accumulate(first, last, T());
};

在上面的代码中,std::accumulate 可以抛出。 如果std::accumulate 抛出会发生什么? T() 会导致内存泄漏? 还是出于某种原因安全? 我怎样才能为此编写异常安全代码?

【问题讨论】:

  • 这段代码没有泄漏。 T() 在本地自动内存中创建一个临时对象。对象在超出范围时被销毁,无论是否抛出异常。

标签: c++ exception


【解决方案1】:

如果 std::accumulate 抛出会发生什么?

临时的T 被销毁(就像正常返回时一样)并将异常传播给调用者。

T() 会导致内存泄漏吗?

除非类 T 本身被严重破坏。

或者出于某种原因它安全吗?

函数是异常安全的。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-09-18
    • 1970-01-01
    • 2021-02-03
    • 2016-10-26
    • 2023-03-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多