Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Explicitly defaulted move constructor

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;
};
like image 226
Tobias Neukom Avatar asked Jun 12 '12 19:06

Tobias Neukom


People also ask

What does a default move constructor do?

A move constructor enables the resources owned by an rvalue object to be moved into an lvalue without copying. For more information about move semantics, see Rvalue Reference Declarator: &&.

Does compiler provide default move constructor?

In C++, the compiler creates a default constructor if we don't define our own constructor. In C++, compiler created default constructor has an empty body, i.e., it doesn't assign default values to data members. However, in Java default constructors assign default values.

Is default constructor a Noexcept move?

Inheriting constructors and the implicitly-declared default constructors, copy constructors, move constructors, destructors, copy-assignment operators, move-assignment operators are all noexcept(true) by default, unless they are required to call a function that is noexcept(false) , in which case these functions are ...

Are move constructors automatically generated?

If a copy constructor, copy-assignment operator, move constructor, move-assignment operator, or destructor is explicitly declared, then: No move constructor is automatically generated. No move-assignment operator is automatically generated.


1 Answers

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.

like image 70
Steve Jessop Avatar answered Oct 17 '22 17:10

Steve Jessop