0
我正在閱讀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;
}
感謝您的參考。 – fetag