view raw
ynimous ynimous - 8 months ago 43
C++ Question

Why does a move constructor require a default constructor for its members?

I was trying to implement a move constructor for a class without a copy constructor. I got an error that the default constructor for a member of the class was missing.

Here's a trivial example to illustrate this:

struct A {
A() = delete;
A(A const&) = delete;
A(A &&a) {}

struct B {
A a;
B() = delete;
B(B const&) = delete;
B(B &&b) {}

Trying to compile this, I get: In constructor ‘B::B(B&&)’: error: use of deleted function ‘A::A()’
B(B &&b) {}
^ note: declared here
A() = delete;

Why is this an error? Any way around it?


Use the constructor's initializer list to initialize the A member. As written, the move constructor uses, as the compiler says, the default constructor for A.

B(B&& b) : a(std::move(b.a)) {}