Do I use std::forward or std::move here?

后端 未结 3 1896
花落未央
花落未央 2021-02-06 01:41

Let\'s say I have:

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

and I i

3条回答
  •  半阙折子戏
    2021-02-06 02:13

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

    std::forward(value)
    

    is suitable.

    std::forward(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 & &&.

    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(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.

提交回复
热议问题