Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Let's say I have:

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

and I inherit from it:

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

Should WHAT_GOES_HERE be std::move or std::forward<T>? Why?

like image 659
user541686 Avatar asked Jun 28 '13 00:06

user541686


1 Answers

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)

is suitable.

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

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

like image 142
jogojapan Avatar answered Sep 20 '22 13:09

jogojapan