mercredi 27 septembre 2017

behavior of synthesised move constructor

I am reading 5th edition and get the following problems. The book lists several cases that a synthesized move operation is defined as deleted. One of which is "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." and also provide an demo code as following:

// 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

However, for both gcc 7.2.1 and clang-900.0.37, the code is runnable, is the book wrong?

Here is the complete test code:

#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;
} 

Aucun commentaire:

Enregistrer un commentaire