C++ Utility 库 - move_if_noexcept 函数
描述
它返回对 arg 的右值引用,除非复制是比移动更好的选择,以提供至少一个强大的异常保证。
声明
以下是 std::move_if_noexcept 函数的声明。
template <class T>
typename conditional < is_nothrow_move_constructible<T>::value ||
!is_copy_constructible<T>::value,
T&&, const T& >::type move_if_noexcept(T& arg) noexcept;
C++11
template <class T>
typename conditional < is_nothrow_move_constructible<T>::value ||
!is_copy_constructible<T>::value,
T&&, const T& >::type move_if_noexcept(T& arg) noexcept;
参数
arg − 它是一个对象。
返回值
它返回对 arg 的右值引用,除非复制是比移动更好的选择,以提供至少一个强大的异常保证。
异常
Basic guarantee − 此函数从不抛出异常。
数据竞争
调用此函数不会引入数据竞争。
示例
在下面的示例中解释了 std::move_if_noexcept 函数。
#include <iostream>
#include <utility>
struct Bad {
Bad() {}
Bad(Bad&&) {
std::cout << "Throwing move constructor called\n";
}
Bad(const Bad&) {
std::cout << "Throwing copy constructor called\n";
}
};
struct Good {
Good() {}
Good(Good&&) noexcept {
std::cout << "Non-throwing move constructor called\n";
}
Good(const Good&) noexcept {
std::cout << "Non-throwing copy constructor called\n";
}
};
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

