查看this question它提到了 C++11 及更高版本:
The move constructor is auto-generated if there is no user-declared copy constructor, copy assignment operator or destructor, and if the generated move constructor is valid (e.g. if it wouldn't need to assign constant members) (§12.8/10).
如果我有以下代码:
class Y
{
public:
Y(const Y&) {}
};
struct hasY {
hasY() = default;
hasY(hasY&&) = default;
Y mem;
};
hasY hy, hy2 = std::move(hy); //this line fails as expected as Y has a user-defined copy constructor.
现在,如果我将默认构造函数添加到 Y:
Y() {}
错误消失了。
哪里说默认构造函数导致移动构造函数的创建?
(使用 VS 2015 更新 2)
最佳答案
class Y
{
public:
Y(const Y&) {}
};
这个类没有默认构造函数,所以
struct hasY {
hasY() = default;
hasY(hasY&&) = default;
Y mem; // << requires default ctor
};
您遇到的错误与移动构造函数无关:
prog.cpp: In function 'int main()':
prog.cpp:13:7: error: use of deleted function 'hasY::hasY()'
hasY hy;
^
prog.cpp:8:5: note: 'hasY::hasY()' is implicitly deleted because the default definition would be ill-formed:
hasY() = default;
关于使用默认构造函数生成的c++移动构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38864967/