使用默认构造函数生成的c++移动构造函数

标签 c++ c++11 constructor

查看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;

http://ideone.com/u46GWS

关于使用默认构造函数生成的c++移动构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38864967/

相关文章:

c++ - 是否可以在不使用映射中的迭代器的情况下访问键值对?

c++ - 为什么默认参数构造函数被称为默认构造函数

java - 当它说类没有接受 String[] 的 static void main 方法时,在哪里添加 main 方法

c++ - 在 C++ 构造函数中为结构数组分配存储空间

c++ - 阶乘递归

c++ - 是否允许构造 unsigned long long?

c++11 - 如果 Mac OS 和 Windows 都使用 x86 指令集,为什么我们要为每个平台重新编译?

C++ - 在 foreach 中复制 vector 给出 "No matching function to call for std::vector<int>::push_back(std::vector<int>&)"

c++ - 是否可以使用 ipropertybag 获取相机属性值?

c++ - while(fin>>a) 或 while(fin.eof()) 将不起作用。在第一种情况下,fin 流变量一直将文件中的最后一个字符作为输入