Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I use std::move or std::forward in move ctors/assignment operators?

Tags:

c++

c++11

Unless I'm wrong it seems like either works just fine - is there a best practice reason to prefer one over the other?

Example:

struct A
{
    A(){}
    A(const A&){ std::cout << "A(const A&)\n"; }
    A(A&&){ std::cout << "A(A&&)\n"; }
};

struct B
{
    B(){}
    B(const B& right) : x(right.x){ std::cout << "B(const B&)\n"; }
    B(B&& right) : x(std::forward<A>(right.x)){ std::cout << "B(B&&)\n"; }

    A x;
};

struct C
{
    C(){}
    C(const C& right) : x(right.x){ std::cout << "C(const C&)\n"; }
    C(C&& right) : x(std::move(right.x)){ std::cout << "C(C&&)\n"; }

    A x;
};

struct D
{
    D(){}
    D(const D& right) : x(right.x){ std::cout << "D(const D&)\n"; }
    D(D&& right) : x(right.x){ std::cout << "D(D&&)\n"; }

    A x;
};

int main()
{
    std::cout << "--- B Test ---\n";
    B b1;
    B b2(std::move(b1));
    std::cout << "--- C Test ---\n";
    C c1;
    C c2(std::move(c1));
    std::cout << "--- D Test ---\n";
    D d1;
    D d2(std::move(d1));
}

Output:

--- B Test ---
A(A&&)
B(B&&)
--- C Test ---
A(A&&)
C(C&&)
--- D Test ---
A(const A&)
D(D&&)
like image 773
David Avatar asked Jan 14 '12 04:01

David


1 Answers

The question is: Are those really the move constructor / assignment operator for the class? Or do they only look like that from the corner of your eye?

struct X{
  X(X&&); // move ctor #1

  template<class T>
  X(T&&); // perfect forwarding ctor #2

  X& operator=(X&&); // move assignment operator #3

  template<class T>
  X& operator=(T&&); // perfect forwarding ass. operator #4
};

In a real move ctor (#1) and move assignment operator (#3), you will never use std::forward, since, as you correctly assessed, you will always move.

Note that std::forward never makes sense without a perfect forwarding template (T&&). That is exactly the case for #2 and #4. Here, you will never use std::move, since you don't know if you actually got an rvalue (A-OK) or an lvalue (not so much).

See this answer of mine for an explanation of how std::forward actually works.

like image 63
Xeo Avatar answered Nov 05 '22 03:11

Xeo