C++11: Move/Copy construction ambiguity?

前端 未结 4 1143
谎友^
谎友^ 2020-12-13 19:39

In C++11 we can define copy and move constructors, but are both allowed on the same class? If so, how do you disambiguate their usage? For example:

Foo MoveA         


        
4条回答
  •  渐次进展
    2020-12-13 20:01

    The "disambiguation" is just your old friend, overload resolution:

    Foo y;
    
    Foo x(y);            // copy
    Foo x(std::move(y)); // move
    

    The expression y in the first example is an lvalue of type Foo, which binds to Foo const & (and also Foo & if you have such a constructor); the type of the expression std::move(y) in the second example is Foo &&, so it'll bind to Foo && (and also Foo const & absent the former).

    In your example, the result of MoveAFoo() is a temporary of type Foo, so it'll bind to the Foo &&-constructor if one is available, and to a const-copy constructor otherwise.

    Finally, in a function returning Foo (by value), the statement return x; is equivalent to return std::move(x); if x is a local variable of type Foo -- this is a special new rule to make the use of move semantics easier.

提交回复
热议问题