为什么移动构造函数的成员需要默认构造函数? [英] Why does a move constructor require a default constructor for its members?
本文介绍了为什么移动构造函数的成员需要默认构造函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我试图为没有复制构造函数的类实现move构造函数。我收到一个错误,提示缺少该类成员的默认构造函数。
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?
推荐答案
使用构造函数的初始化程序列表初始化 A
成员。按照编写程序的说法,正如编译器所说,move构造函数使用 A
的默认构造函数。
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)) {}
这篇关于为什么移动构造函数的成员需要默认构造函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文