mardi 30 octobre 2018

Copy constructor called (and not the move constructor) even with a variable used only once (so like a temporary one)

Code :

#include <iostream>

class A {
public:
    A() {
        std::cout << "Default constructor" << std::endl;
    }

    A(const A& a) {
        std::cout << "Copy constructor" << std::endl;
    }

    A(A&& a) {
        std::cout << "Move constructor" << std::endl;
    }
};

int main()
{
    {//case 1
        A b = A(A());
    }
    std::cout << std::endl;
    {// case 2
        A a;
        A b = A(a);
    }
    std::cout << std::endl;
    {//case 3
        A a;
        A b = A(std::move(a));
    }
}

Output (with -O3 compilation flag) :

#case 1
Default constructor

#case 2
Default constructor
Copy constructor

#case 3
Default constructor
Move constructor

In case 2, why is the copy constructor called even with maximum optimization level (-O3) ? I was expecting the compiler to detect that the variable 'a' is like being temporary (because used only for the construction of 'b') and to rather use the move constructor (like in case 3) or the default constructor (like in case 1). And second question : Why in case 1, the default constructor is called only once whereas I would expect a default construction + a move construction ?

Aucun commentaire:

Enregistrer un commentaire