如果传递给std :: swap的对象在交换期间抛出异常怎么办? [英] What if an object passed into std::swap throws an exception during swapping?

查看:85
本文介绍了如果传递给std :: swap的对象在交换期间抛出异常怎么办?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

C ++标准保证 std :: swap 不会抛出异常.但是,如果要交换的对象在交换期间引发异常怎么办?接下来,调用方应如何发现发生了异常?呼叫者应采取什么措施?

The C++ standard guarantees that std::swap will throw no exception. However, what if an object to swap throws an exception during swapping? Next, how should the caller find an exception has happened? and what measures should the caller take?

PS:构造函数抛出异常是很常见的.

PS: It is very common that a constructor throws an exception.

struct A
{
    A(const A&)
    {
        throw 1;
    }

    A& operator =(const A&)
    {
        throw 2;
        return *this;
    }
};

int main()
{
    A a1, a2;
    std::swap(a1, a2); // An exception happened, but the caller doesn't know.
    // How to do here ???
}

推荐答案

C ++标准保证std :: swap不会抛出异常.

The C++ standard guarantees that std::swap will throw no exception.

不,不是.请参阅20.2.2或参考.对于两个 std :: swap 重载,有两个noexcept规范:

No, it doesn't. See 20.2.2 or the reference. There are two noexcept specifications for the two std::swap overloads:

template<class T> void swap(T& a, T& b)
noexcept(noexcept(
    std::is_nothrow_move_constructible<T>::value &&
    std::is_nothrow_move_assignable<T>::value
))

template<class T, size_t N>
void swap(T (&a)[N], T (&b)[N])    
noexcept(noexcept(swap(*a, *b)))

不满足这些条件时, std :: swap 可能会抛出并捕获它.

When these conditions aren't satisfied, std::swap can throw and you can catch it.

对于您所介绍的课程,谓词 std :: is_nothrow_move_constructible std :: is_nothrow_move_assignable 为假,因此实例化 std :: swap< A> 不具有不掷球的保证.从此交换中捕获异常是完全合法的.

In case of the class you have presented, the predicates std::is_nothrow_move_constructible and std::is_nothrow_move_assignable are false, so the instantiation std::swap<A> doesn't have the no-throw guarantee. It's perfectly legal to catch exceptions from this swap.

这篇关于如果传递给std :: swap的对象在交换期间抛出异常怎么办?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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