mercredi 23 mars 2016

why does c++ generate a constructor in the following case?

I have a class A

struct A{
    A(){}

    A(int x): d(x) {}

    A(const A& a): d(a.d) {
        std::cout << "copy construction" << std::endl;
    }

    A(A&& a): d(a.d){
        std::cout << "move construction" << std::endl;
    }

    A& operator=(const A& a){
        std::cout << "copy assignment" << std::endl;
        d = a.d;
        return *this;
    }

    A& operator=(A&& a){
        std::cout << "move assignment" << std::endl;
        d = a.d;
        return *this;
    }

    int d;
};

and a function func

A func(){
    return A(3);
}

if I do this

A x;
x = func();

the output is "move assignment" as expected but if I construct A like this

A x = func();

then nothing is printed as if c++ generates its own move constructor and refuses to use the defined one.

I'd really like to understand this.

Thank you for explanations.

Aucun commentaire:

Enregistrer un commentaire