std :: move和std :: forward之间有什么区别 [英] What's the difference between std::move and std::forward

查看:137
本文介绍了std :: move和std :: forward之间有什么区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在这里看到了:
移动构造函数调用基类移动构造子

有人可以解释:


  1. 两者之间的区别 std :: move std :: forward ,最好带有一些代码示例?

  2. 如何轻松思考它,以及何时使用哪个

  1. the difference between std::move and std::forward, preferably with some code examples?
  2. How to think about it easily, and when to use which


推荐答案

std :: move 接受一个对象,并允许您将其视为临时对象(右值)。尽管这不是语义上的要求,但通常,接受对右值的引用的函数会使它无效。当您看到 std :: move 时,表明此后不应使用该对象的值,但仍可以分配一个新值并继续使用它。

std::move takes an object and allows you to treat it as a temporary (an rvalue). Although it isn't a semantic requirement, typically a function accepting a reference to an rvalue will invalidate it. When you see std::move, it indicates that the value of the object should not be used afterwards, but you can still assign a new value and continue using it.

std :: forward 有一个用例:将模板化函数参数(在函数内部)转换为值调用者用来传递它的类别(左值或右值)。这允许将rvalue参数作为rvalue传递,并将lvalues作为lvalues传递,这是一种称为完美转发的方案。

std::forward has a single use case: to cast a templated function parameter (inside the function) to the value category (lvalue or rvalue) the caller used to pass it. This allows rvalue arguments to be passed on as rvalues, and lvalues to be passed on as lvalues, a scheme called "perfect forwarding."

To 插图

void overloaded( int const &arg ) { std::cout << "by lvalue\n"; }
void overloaded( int && arg ) { std::cout << "by rvalue\n"; }

template< typename t >
/* "t &&" with "t" being template param is special, and  adjusts "t" to be
   (for example) "int &" or non-ref "int" so std::forward knows what to do. */
void forwarding( t && arg ) {
    std::cout << "via std::forward: ";
    overloaded( std::forward< t >( arg ) );
    std::cout << "via std::move: ";
    overloaded( std::move( arg ) ); // conceptually this would invalidate arg
    std::cout << "by simple passing: ";
    overloaded( arg );
}

int main() {
    std::cout << "initial caller passes rvalue:\n";
    forwarding( 5 );
    std::cout << "initial caller passes lvalue:\n";
    int x = 5;
    forwarding( x );
}

如霍华德所言,这两个函数也有相似之处,只是简单地转换为引用类型。但是,除了这些特定的用例(覆盖了右值引用强制转换的99.9%的实用性)之外,您应该直接使用 static_cast 并为您的工作写一个很好的解释。

As Howard mentions, there are also similarities as both these functions simply cast to reference type. But outside these specific use cases (which cover 99.9% of the usefulness of rvalue reference casts), you should use static_cast directly and write a good explanation of what you're doing.

这篇关于std :: move和std :: forward之间有什么区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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