合成移动构造函数的行为
问题描述:
我正在阅读C++ Primer第5版,并获得以下问题。本书列举了几种合成移动操作被定义为删除的情况。其中之一是“与复制构造函数不同,如果类的成员定义了自己的拷贝构造函数,但不定义移动构造函数,或者该类的成员没有定义,则移动构造函数被定义为删除它自己的复制操作,编译器无法合成移动构造函数,类似于移动赋值。“ 并还提供了一个演示代码如下:合成移动构造函数的行为
// assume Y is a class that defines its own copy constructor but not a move constructor
struct hasY {
hasY() = default;
hasY(hasY&&) = default;
Y mem; // hasY will have a deleted move constructor
};
hasY hy, hy2 = std::move(hy); // error: move constructor is deleted
然而,对于GCC 7.2.1和铛,900.0.37,代码可运行的,是书错了吗?
下面是完整的测试代码:
#include <iostream>
struct Y {
Y() { std::cout << "Y()" << std::endl; }
Y(const Y&) { std::cout << "Y(const Y&)" << std::endl; }
//Y(Y&&) { cout << "Y(Y&&)" << endl; }
};
// assume Y is a class that defines its own copy constructor but not a move constructor
struct hasY {
hasY() = default;
hasY(hasY&&) = default;
Y mem; // hasY will have a deleted move constructor
};
int main() {
hasY hy, hy2 = std::move(hy); // error: move constructor is deleted
return 0;
}
答
书中正确地描述由C++ 11标准中规定的行为。然而,规定的行为已经改变为C++ 14,它采用了分辨率为Defect Report #1402 "Move functions too often deleted"
感谢您的参考。 – fetag