std::move_if_noexcept
来自cppreference.com
该页由英文版wiki使用Google Translate机器翻译而来。
该翻译可能存在错误或用词不当。鼠标停留在文本上可以看到原版本。你可以帮助我们修正错误或改进翻译。参见说明请点击这里. |
在头文件 <utility> 中定义
|
||
template< class T > typename std::conditional< |
(C++11 起) | |
move_if_noexcept
获得一个右值引用它的参数,如果它的移动构造函数不会抛出异常,否则得到一个左值,它的参数。它通常用于移动语义组合具有很强的异常保证.原文:
move_if_noexcept
obtains an rvalue reference to its argument if its move constructor does not throw exceptions, otherwise obtains an lvalue reference to its argument. It is typically used to combine move semantics with strong exception guarantee.例如,std::vector::resize偶尔会分配新的存储,然后移动或复制的元素从旧存储到新的存储。在此操作过程中如果发生异常,std::vector::resize撤消它所做的一切到这点,这是唯一可能std::move_if_noexcept来决定是否使用移动建设或拷贝构造.
原文:
For example, std::vector::resize occasionally allocates new storage and then moves or copies elements from old storage to new storage. If an exception occurs during this operation, std::vector::resize undoes everything it did to this point, which is only possible if std::move_if_noexcept was used to decide whether to use move construction or copy construction.
目录 |
[编辑] 参数
x | - | 对象物的移动或复制
|
[编辑] 返回值
[编辑] 例外
[编辑] 示例
#include <iostream> #include <utility> struct Bad { Bad() {} Bad(Bad&&) // may throw { std::cout << "Throwing move constructor called\n"; } Bad(const Bad&) // may throw as well { std::cout << "Throwing copy constructor called\n"; } }; struct Good { Good() {} Good(Good&&) noexcept // will NOT throw { std::cout << "Non-throwing move constructor called\n"; } Good(const Good&) {}; }; int main() { Good g; Bad b; Good g2 = std::move_if_noexcept(g); Bad b2 = std::move_if_noexcept(b); }
输出:
Non-throwing move constructor called Throwing copy constructor called
[编辑] 复杂度
常数
[编辑] 另请参阅
(C++11) |
转发函数的参数 (函数模板) |
(C++11) |
获得一个右值引用 (函数模板) |