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).
Aucun commentaire:
Enregistrer un commentaire