mercredi 27 juin 2018

Why is the move constructor involved here

I have this piece of C++ code:

class Args {};

class MyClass {
  public:
  MyClass(Args& a) {}
  MyClass(MyClass &&) = delete;
};

int main() {

  Args a;
  MyClass c1 = MyClass(a);
  MyClass c2 = a;
  MyClass c3(a);

  return 0;
}

This does not compile because the construction of objects c1 and c2 seem to involve the class's move constructor:

error: use of deleted function ‘MyClass::MyClass(MyClass&&)’

It seems as if the compiler wants to create temporary object and then move them to c1 and c2. Why is this happening? Shouldn't all three statements just call the MyClass(Args& a) constructor?

On the other hand, if I do create the move constructor the program compiles fine and the move constructor is never called!!!

Aucun commentaire:

Enregistrer un commentaire