For this program
#include <iostream>
using std::cout;
struct C
{
C() { cout << "Default C called!\n"; }
C(const C &rhs) { cout << "CC called!\n"; }
};
const C f()
{
cout << "Entered f()!\n";
return C();
}
int main()
{
C a = f();
C b = a;
return 0;
}
the output I get is:
Entered f()!
Default C called!
CC called!
Since f()
is returning by value, it should return a temporary. As T a = x;
is T a(x);
, wouldn't it call the copy constructor for the construction of a
, with the temporary passed-in as its argument?
Look up Return Value Optimization. This is turned on by default. If you are on Windows using MSVC 2005+ you can use
/Od
to turn this off and get the desired result (or-fno-elide-constructors
on GCC). Also, for MSVC see this article.