I am new to c++, and I read a little bit on return value optimization on wiki and also this website, however I am still curious how the following behavior happens:
using namespace std;
class A
{
public:
A() {cout << "A Ctor" << endl;}
A(const A &a) {cout << "A copy Ctor" << endl;}
};
A Foo()
{
A a;
return a;
}
int _tmain(int argc, _TCHAR* argv[])
{
cout << "Foo()" << endl;
Foo();
cout << "Foo() and new object" << endl;
A b(Foo());
return 0;
}
and the output is:
Foo()
A Ctor
A copy Ctor
Foo() and new object
A Ctor
A copy Ctor
my question is, why Foo();
and A b(Foo());
both only triggered one copy constructor call? Does that mean the returned copied value from Foo()
can be used to construct object b
in that place so that b's constructor is not needed to be called again? This was based on visual studio 2010.