move_if_noexcept
描述 (Description)
它返回对arg的右值引用,除非复制是一个比提供至少强大的异常保证更好的选择。
声明 (Declaration)
以下是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;
参数 (Parameters)
arg - 这是一个对象。
返回值 (Return Value)
它返回对arg的右值引用,除非复制是一个比提供至少强大的异常保证更好的选择。
异常 (Exceptions)
Basic guarantee - 此函数永远不会抛出异常。
数据竞争 (Data races)
调用此函数不会引入任何数据争用。
例子 (Example)
在下面的例子中解释了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