mardi 1 novembre 2016

Compiler complaining about deleted copy constructor when move constructor is expected to be called instead

I have the following code:

#include <iostream>

class B{
public:
    //this should all be generated by default but
    //throwing them in here just to be sure
    B() = default;
    B(const B& b) = default;
    B& operator=(const B& b) = default;
    B(B&& b) = default;
    B& operator=(B&& b) = default;
};

class A {
public:
    A(B x) : x_(x) {}
    A(const A& a) = delete;
    A& operator=(const A& a) = delete;
    //move operations should be generated by compiler?
private:
    B x_;
};

int main() {
    A a = A(B());
}

I'm expecting this to compile and an A to be created using it's move constructor, but instead this fails with the following message:

error: use of deleted function ‘A::A(const A&)’ A a = A(B()); note: declared here A(const A& a) = delete;

Of course adding the move operations and marking them with the default keywords eliminates the problem. Should I assume that the move operations were not generated by the compiler, why is that? Why is the copy constructor prefered instead? I'm using gcc to compile.

Aucun commentaire:

Enregistrer un commentaire