Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
403 views
in Technique[技术] by (71.8m points)

c++ - 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 {
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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...