如果传递到 std::swap 的对象在交换过程中引发异常怎么办?
What if an object passed into std::swap throws an exception during swapping?
C++标准保证std::swap
不会抛出异常。但是,如果要交换的对象在交换期间引发异常怎么办?接下来,调用方应如何查找已发生的异常?呼叫者应采取哪些措施?
PS:构造函数引发异常是很常见的。
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 不会引发异常。
不,它没有。请参阅 20.2.2 或参考。对于这两种std::swap
重载,有两种例外规范:
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
可以投掷,你可以接住它。
对于您提供的类,谓词 std::is_nothrow_move_constructible
和 std::is_nothrow_move_assignable
为 false,因此实例化std::swap<A>
没有不抛出保证。从此交换中捕获异常是完全合法的。
该标准通常不保证交换不会抛出。
从 20.2.2/1:
模板无效交换(T&a,T&b)noexcept(见下文);
备注:noexcept 中的表达式等效于:
is_nothrow_move_constructible<T>::value && is_nothrow_move_assignable<T>::value
相关文章:
- 是否删除在对象构造过程中创建的对象
- 如何在鼠标挂钩过程中检测拖动
- clang 插件:在编译过程中修改 AST
- Adafruit 羽毛RFM69HCW在使用过程中会冻结,需要硬重置
- c++:交换向量中所有元组的第一个和第二个元素
- 线程过程中的线程同步问题
- MySQL 连接器/C++.尝试在此过程中停止连接到数据库
- C++ 在编译过程中 strtok 函数 Eclipse 说没有在范围内声明?
- 在调用过程中删除 std::函数
- 动态矩阵特征分解过程中的误差
- cmake在构建过程中使用另一个工具检测标志
- 在模板参数推导过程中丢失限定符
- 升压过程中的管道缓冲区大小
- 如何在插入过程中更改插入的值
- 在PostgreSQL函数或过程中使用C++代码
- 用c++交换短语中单词的前两个字母
- Vulkan:设备在缓冲区复制过程中丢失
- 错误:使用复制和交换习惯用法的交换函数中"operator="的重载不明确
- 如何解决导入dll过程中Viual Studio中的并排配置错误
- 如果传递到 std::swap 的对象在交换过程中引发异常怎么办?