C++11: Move/Copy construction ambiguity?

前端 未结 4 1136
谎友^
谎友^ 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:08

    Foo MoveAFoo() {
      Foo f;
      return f;
    }
    

    This is definition of function MoveAFoo that returns object of type Foo. In its body local Foo f; is created and destructed when it goes out of its scope.

    In this code:

    Foo x = MoveAFoo();
    

    object Foo f; is created inside of MoveAFoo function and directly assigned into x, which means that copy constructor is not called.

    But in this code:

    Foo x;
    x = MoveAFoo();
    

    object Foo f; is created inside of MoveAFoo function, then the copy of f is created and stored into x and original f is destructed.

提交回复
热议问题