在这里是否需要`std :: move`? [英] Is `std::move` necessary here?

查看:138
本文介绍了在这里是否需要`std :: move`?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下片段中是否需要 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));
}

至于我知道 call code>接受右值引用..但是由于右值引用本身是一个左值,为了调用 swap(std :: function< void(int)>&& / code>我必须重新转换为一个右值引用 std :: move



我的推理是正确的还是 std :: move 在这种情况下可以省略(如果可以,为什么?)

解决方案

std :: function :: swap 不会通过rvalue引用参数。它只是一个常规非 - const lvalue引用。所以 std :: move 是无用的(并且可能不应该编译,因为右值引用不允许绑定到非 - const lvalue references)。



other_function 也不需要是一个右值引用。 p>

Is std::move necessary in the following snippet?

std::function<void(int)> my_std_function;

void call(std::function<void(int)>&& other_function)
{
  my_std_function.swap(std::move(other_function));
}

As far as I know call() accepts a rvalue reference.. but since the rvalue reference is itself an lvalue, in order to call swap(std::function<void(int)>&&) I have to re-cast this to an rvalue reference with std::move

Is my reasoning correct or std::move can be omitted in this case (and if it can, why?)

解决方案

std::function::swap does not take its parameter by rvalue reference. It's just a regular non-const lvalue reference. So std::move is unhelpful (and probably shouldn't compile, since rvalue references aren't allowed to bind to non-const lvalue references).

other_function also doesn't need to be an rvalue reference.

这篇关于在这里是否需要`std :: move`?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆