合成移动构造函数的行为
behavior of synthesised move constructor
我正在阅读 C++ Primer 第 5 版并遇到以下问题。书中列出了几种将合成移动操作定义为删除的情况。其中之一是 "Unlike the copy constructor, the move constructor is defined as deleted if the class has a member that defines its own copy constructor but does not also define a move constructor, or if the class has a member that doesn't define its own copy operations and for which the compiler is unable to synthesize a move constructor. Similarly for move-assignment."
并提供演示代码如下:
// 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和clang-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"
的决议
我正在阅读 C++ Primer 第 5 版并遇到以下问题。书中列出了几种将合成移动操作定义为删除的情况。其中之一是 "Unlike the copy constructor, the move constructor is defined as deleted if the class has a member that defines its own copy constructor but does not also define a move constructor, or if the class has a member that doesn't define its own copy operations and for which the compiler is unable to synthesize a move constructor. Similarly for move-assignment." 并提供演示代码如下:
// 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和clang-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"
的决议