Explicitly defaulted move constructor
Asked Answered
H

2

11

According to the c++11 standard a default move constructor is only generated if:

  • X does not have a user-declared copy constructor, and
  • X does not have a user-declared copy assignment operator,
  • X does not have a user-declared move assignment operator,
  • X does not have a user-declared destructor, and
  • the move constructor would not be implicitly defined as deleted.

Can I still explicitly default it? Seems to work correctly in clang. Like this for example:

class MyClass {
private:
  std::vector<int> ints;
public:
  MyClass(MyClass const& other) : ints(other.ints) {}
  MyClass(MyClass&& other) = default;
};
Hoagy answered 12/6, 2012 at 19:9 Comment(0)
I
14

The motivation for that rule is that if the default copy constructor doesn't work for your class, then chances are the default move constructor won't work either (rule of 5, or whatever we're up to in C++11). So yes, you can explicitly default it, on your honor as a programmer that it'll work.

In your example code you could instead remove the copy constructor, since it does the same as the default.

Incoordination answered 12/6, 2012 at 19:21 Comment(0)
P
5

Yes, you can always explicitly invoke the default generation for functions that can be automatically generated with = default. That's what the syntax is for.

Parishioner answered 12/6, 2012 at 19:26 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.