Original code
#include <iostream>
int global;
struct A
{
A(){}
A(const A&x){
++global;
}
~A(){}
};
A foo()
{
A a;
return a;
}
int main()
{
A x = foo();
std::cout << global;
}
Output would be 0
on an optimized compiler supporting Named Return Value Optimization.
When I change the definition of foo
to
A foo()
{
{
A a;
return a;
}
}
I get 1
as the output i.e copy c-tor gets called once. What could be the possible reason? Introducing a dummy scope changes the behavior of the code completely. What am I missing?
I tested it on g++ compiler. Any compiler guy around here who can explain the scenario in some implementation-specific manner?
EDIT
I tested it on clang and it optimizes the call to the copy c-tor even in the second case.
Andrew Pinski (gcc guy) confirmed that this is indeed a case of missed optimization on g++.