我使用std :: forward或std :: move这里? [英] Do I use std::forward or std::move here?

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

问题描述

假设我有:

template<class T>
struct NodeBase
{
    T value;
    NodeBase(T &&value)
        : value(value) { }
};

并继承它:

template<class T>
struct Node : public NodeBase<T>
{
    Node(T &&value)
        : NodeBase( WHAT_GOES_HERE (value)) { }
};

WHAT_GOES_HERE std :: move std :: forward< T> ?为什么?

推荐答案

由于在 Node< T& c>未知 T 是一个普通类型(即不是引用)还是引用

Since in the implementation of the constructor of Node<T> it is unknown whether T is a plain type (i.e. not a reference), or a reference,

std::forward<T>(value)

std :: forward< T>(value) T&&& 绑定到右值或左值。这里是这种情况,因为在构造函数中,我们不知道 T&&& 是否等同于 U&& c $ c>对于某些纯类型 U ,或等价于 U& &&&&&< / code>。

std::forward<T>(value) is the right choice whenever it isn't known whether T && binds to an rvalue or an lvalue. This is the case here because in the constructor we don't know whether T && is equivalent to U && for some plain type U, or equivalent to U & &&.

无论 T 使用 std :: forward 或在不同时间确定的函数调用(例如在您的示例中, T 是在 Node 模板被实例化时确定的)。

It doesn't matter whether T is deduced in the function call that uses std::forward or determined at a different time (such as in your example, where T is determined at the time when the Node template is instantiated).

std :: forward< T>(value)将以与调用者直接调用基类构造函数相同的方式调用继承的构造函数。也就是说,当 value 是一个左值,并且当 value 是一个右值时,它会调用一个左值。

std::forward<T>(value) will call the inherited constructor in the same way as if the base class constructor had been called directly by the caller. I.e., it will call it on an lvalue when value is an lvalue, and on an rvalue when value is an rvalue.

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

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