The following code generates output:
copy constructor: i = 2
I don't understand why the copy constructor doesn't get called returning from f1()
. I'm using Visual C++ V12. I thought it might be return value optimization but I get the same output whether I'm compiling Debug or Release.
class C
{
public:
C(int i) { i_ = i; }
C(C const &rhs)
{
i_ = rhs.i_;
std::printf("copy constructor: i = %i\n", i_);
}
int i_;
};
C f1()
{
return C(1);
}
C f2()
{
C c(2);
return c;
}
int main()
{
C c1 = f1();
C c2 = f2();
return 0;
}