Should a move constructor take a const or non-const rvalue reference?

前端 未结 4 970
死守一世寂寞
死守一世寂寞 2020-11-30 03:29

In several places I\'ve seen the recommended signatures of copy and move constructors given as:

struct T
{
    T();
    T(const T& other);
    T(T&&a         


        
4条回答
  •  隐瞒了意图╮
    2020-11-30 03:35

    In addition to what is said in other answers, sometimes there are reasons for a move constructor or a function to accept a const T&&. For example, if you pass the result of a function that returns a const object by value to a constructor, T(const T&) will be called instead of T(T&&) as one would probably expect (see function g below).

    This is the reason behind deleting overloads that accept constT&& for std::ref and std::cref instead of those that accept T&&.

    Specifically, the order of preference during overload resolution is as follows:

    struct s {};
    
    void f (      s&);  // #1
    void f (const s&);  // #2
    void f (      s&&); // #3
    void f (const s&&); // #4
    
    const s g ();
    s x;
    const s cx;
    
    f (s ()); // rvalue        #3, #4, #2
    f (g ()); // const rvalue  #4, #2
    f (x);    // lvalue        #1, #2
    f (cx);   // const lvalue  #2
    

    See this article for more details.

提交回复
热议问题