#include <iostream>
#include <time.h>
class A
{
public:
A() { std::cout << "a ctor\n"; }
A(const A&) { std::cout << "a copy ctor\n"; }
A(A&&) { std::cout << "a move ctor\n"; }
};
A f(int i)
{
A a1;
return i != 0 ? a1 : A{};
}
int main()
{
srand(time(0));
f(rand());
return 0;
}
The output is:
a ctor
a copy ctor
I would expect that a1 in f() will be moved not copied. If I change f() just a little bit, it's not a copy anymore but a move:
A f(int i)
{
A a1;
if (i != 0)
{
return a1;
}
return A{};
}
The output is:
a ctor
a move ctor
Could you explain me how does this work? GCC 9.3.0
(edit: added random number to prevent RVO)