看看this question,它提到了C++11,后来只提到了
如果没有用户声明的复制构造函数、复制赋值操作符或析构函数,以及生成的移动构造函数有效(例如,如果不需要分配常量成员),则自动生成移动构造函数(§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)
发布于 2016-08-10 05:46:24
它与move构造函数无关,它是关于默认构造函数的。试试这个:
class Y
{
public:
Y(const Y&) {}
};
struct hasY {
hasY() = default;
hasY(hasY&&) = default;
Y mem;
};
hasY hy; // This will cause an error because there is no default constructor现在,如果添加默认构造函数:Y(){},则错误将消失。
正如@M.M所评论的,在这种情况下,复制构造函数将被调用。
您可以尝试以下代码:
class Y{
public:
Y(){std::cout << "Default constructor\n";}
Y(const Y&) {std::cout << "Copy constructor\n";}
};
struct hasY {
hasY() = default;
hasY(hasY&&) = default;
Y mem;
};
int main(){
hasY hy;
hasY h=std::move(hy);
}它将印刷:
默认构造函数 复制构造函数
如果要使类不可移动,则应自行删除移动构造函数( Y(Y&&)=delete; )。
发布于 2016-08-10 05:45:48
class Y
{
public:
Y(const Y&) {}
};这个类没有默认构造函数,所以
struct hasY {
hasY() = default;
hasY(hasY&&) = default;
Y mem; // << requires default ctor
};您所得到的错误与move构造函数无关:
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;http://ideone.com/u46GWS
发布于 2016-08-10 05:45:26
它说默认构造函数在哪里导致移动构造函数的创建?
移动构造函数的创建与默认构造函数的存在或不存在之间没有任何关系。
来自C++11标准:
12.8复制和移动类对象 ..。 9如果类X的定义没有显式声明移动构造函数,则将隐式声明为defaulted当且仅当 -X没有用户声明的复制构造函数, -X没有用户声明的副本赋值操作符, -X没有用户声明的移动赋值操作符, -x没有用户声明的析构函数,并且 -移动构造函数不会被隐式定义为已删除。
https://stackoverflow.com/questions/38864967
复制相似问题