std::move在以下片段中是否有必要?
std::function<void(int)> my_std_function;
void call(std::function<void(int)>&& other_function)
{
my_std_function.swap(std::move(other_function));
}
Run Code Online (Sandbox Code Playgroud)
据我所知call()接受一个右值引用..但由于右值引用本身就是一个左值,为了调用swap(std::function<void(int)>&&)我必须将它重新转换为右值引用std::move
我的推理是正确的还是std::move在这种情况下可以省略(如果可以,为什么?)
Nic*_*las 18
std::function::swap不通过右值参考获取其参数.它只是一个常规的非const左值参考.因此std::move无益(并且可能不应该编译,因为不允许rvalue引用绑定到非const左值引用).
other_function 也不需要是右值参考.
Jar*_*d42 11
签名是
void std::function<Sig>::swap( function& other )
Run Code Online (Sandbox Code Playgroud)
所以代码不应该编译std::move(msvc有扩展名允许这种绑定:/)
当你采用r值引用时,我认为在你的情况下你想要的是一个简单的赋值:
std::function<void(int)> my_std_function;
void call(std::function<void(int)>&& other_function)
{
my_std_function = std::move(other_function); // Move here to avoid copy
}
Run Code Online (Sandbox Code Playgroud)