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

后端 未结 3 1831
花落未央
花落未央 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:31

    T isn't deduced in your example. The T is a class template parameter, not a function template parameter. So assuming you will not use a reference type as T, T&& will be an rvalue-reference to T, so it will only bind to rvalues of type T. these will be safe to move so you can use std::move here.

    template
    struct Node : public NodeBase
    {
        Node(T &&value)
            : NodeBase( std::move (value)) { }
    };
    
    int main()
    {
        int i = 3;
    
        Node x(42); // ok
        Node y(std::move(i)); // ok
        Node z(i); // error
    }
    

    std::forward is normally only for places where you have a deduced type that may either be an lvalue-reference or rvalue-reference.

    template
    void f(T&& x)
    {
        ... std::forward(x) ...
    }
    

    Because T&& may actually be either an lvalue-reference or rvalue-reference. This is only because T is deduced in this context.

提交回复
热议问题