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

。_饼干妹妹 提交于 2019-11-30 01:20:18

问题


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 {
public:
        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:

move_without_default.cc: In constructor ‘B::B(B&&)’:
move_without_default.cc:15:11: error: use of deleted function ‘A::A()’
  B(B &&b) {}
           ^
move_without_default.cc:6:2: note: declared here
  A() = delete;
  ^

Why is this an error? Any way around it?


回答1:


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)) {}



回答2:


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

The move constructor that you defined default-constructs a member. If you default construct any members, then the default constructor is required for those members.

A constructor (be it regular, copy or move) default initializes the members that are not listed in the member initialization list nor have a default member initialization. B::a is not in the member initialization list of the move constructor (it doesn't have an initialization list at all) and it has no default member initialization.

Any way around it?

Most simply, use the default move constructor:

B(B&&) = default;

The default move constructor move-constructs the members.




回答3:


A move constructor in general does not have to provide default initialization. Your move constructor does.

A move constructor is still a constructor. And therefore, it must initialize all subobjects. If you don't provide explicit initialization, then it will attempt to default initialize them. And if it can't do that, you get an error.

So you can either initialize them (perhaps moving from b), or just use = default with your move constructor and let the compiler do it's job.



来源:https://stackoverflow.com/questions/39297334/why-does-a-move-constructor-require-a-default-constructor-for-its-members

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!