如果您想使用非标准版本来创建 noexcept 移动 ctor 使用 rvalues 仅是有条件地 noexcept 与您使用的值,您可以使用此版本:
namespace estd {
template<class T, class U = T, std::enable_if_t<
std::is_move_constructible<std::remove_reference_t<T>>::value &&
std::is_assignable<std::remove_reference_t<T>, std::remove_reference_t<U>&&>::value &&
!std::is_lvalue_reference<U>::value,
int> = 0
>
T rval_exchange(T& obj, U&& new_value) noexcept(
std::is_nothrow_move_constructible<std::remove_reference_t<T>>::value &&
std::is_nothrow_assignable<std::remove_reference_t<T>, std::remove_reference_t<U>&&>::value
)
{
T old_value {std::move(obj)};
obj = std::move(new_value);
return old_value;
}
} // namespace estd
如果您使用左值引用作为要在obj 中移动的值(即new_value 必须是绑定到右值的右值引用),如果您使用不可移动构造的类型 T,则模板将被禁用,或者如果移动构造不适用于该右值。
这样,您可以定义 noexcept 移动 ctor。 Demo here。我将函数限制为仅右值的原因是因为通常复制不是noexcept,即使并非总是如此,并且因为exchange 应该用于移动ctors,而不是noexcept使那些 ctors 不是 noexcept,这显然是不好的。
void do_stuff() noexcept
{ /*...*/ }
class Sample
{
std::string mBody;
public:
Sample(const std::string& body = ""): mBody {body} {}
Sample(const Sample& s): mBody {s.mBody} {
printf("%s\n", __PRETTY_FUNCTION__); // noexcept
}
Sample& operator=(const Sample& s) {
mBody = s.mBody;
printf("%s\n", __PRETTY_FUNCTION__); // noexcept
return *this;
}
Sample(Sample&& dying) noexcept(
noexcept(do_stuff()) &&
noexcept(estd::rval_exchange(dying.mBody, {}))
):
mBody {estd::rval_exchange(dying.mBody, {})}
{
do_stuff(); // noexcept
printf("%s\n", __PRETTY_FUNCTION__); // noexcept
}
Sample& operator=(Sample&& dying) noexcept(
noexcept(do_stuff()) &&
noexcept(estd::rval_exchange(dying.mBody, {}))
)
{
mBody = estd::rval_exchange(dying.mBody, {});
do_stuff();
printf("%s\n", __PRETTY_FUNCTION__); // noexcept
return *this;
}
std::string body() const noexcept {return mBody;}
};
int main()
{
std::cout << std::boolalpha;
Sample rval{"wow such string very content"};
Sample dummy;
std::cout << noexcept( Sample(std::move(rval)) ) << std::endl; // prints true
std::cout << noexcept( dummy = std::move(rval) ) << std::endl; // prints true
// The rest only to show that move semantics actually work
Sample f (std::move(rval)); // Calls move ctor
std::cout << rval.body() << std::endl; // prints empty line, empty string moved in rval
std::cout << f.body() << std::endl; // prints wow such string very content
// estd::rval_exchange(f, rval); // Fails to compile bc rval is an lvalue reference, template disabled
std::cout << (estd::rval_exchange(f, std::move(rval))).body() << std::endl;
// Ok, calls move ctor and move assignment (in estd::rval_exchange) and
// prints wow such string very content
std::cout << f.body() << std::endl; // empty line, rval (empty) moved in f
std::cout << "end" << std::endl;
}