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.
Return Value Optimization (RVO) states that a compiler can elide one or both copies, but it is not required. This means that:
Is free to do 0, 1, or 2 copy constructors:
2 - In function Foo(),
A a
creates anA
. When it tries to return, it copies theA
into the return value; the resulting initializationA a(Foo());
copies the result ofFoo()
into a newA
.1 - One of those copies doesn't happen (probably the copy into
Foo
's return value.0 - Neither of those copies happen. The
A a
created inside ofFoo
directly becomes theA
created in this line:A a(Foo());
Msdn has a lot of detail about how the visual c++ compiler handles RVO. It has some neat code examples that explain how it effectively works.