mardi 26 décembre 2017

Why Copy constructor is called along with Move Constructor?

This problem seems strange but I've checked with multiple compilers. In my code, I have a Move Constructor and a copy constructor as

class A {
    int val;
public:
    A(int var) : val(var)  {
    }
    A( A && a1) {
        cout<<"M Value -> "<<a1.val<<endl;
        cout<<"Move Cons..."<<endl;
     }
    A(const A & a1) {
        cout<<"Copy Cons.."<<endl;
        cout<<"Value -> "<<a1.val<<endl;
    }
};

If I write my main function as

int main()
{
    vector<A> v1;
    A a2(200);
    v1.push_back(move(a2));              
}

The output is

M Value -> 200
Move Cons...

Which is expected, but if I changed my main function as

int main()
{
    vector<A> v1;
    A a2(200);
    v1.push_back(A(100));
    v1.push_back(move(a2));

}

I get the following output

M Value -> 100
Move Cons...
M Value -> 200
Move Cons...
Copy Cons..   // unexpected
Value -> 0    // unexpected

Can anyone help me in understanding where and how this copy constructor gets called.. that too with value 0

Thanks

Aucun commentaire:

Enregistrer un commentaire