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

前端 未结 1 1676
無奈伤痛
無奈伤痛 2021-01-04 22:39

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(){}
         


        
相关标签:
1条回答
  • 2021-01-04 23:28

    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.

    0 讨论(0)
提交回复
热议问题