Return Value Optimization (RVO) states that a compiler can elide one or both copies, but it is not required. This means that:
A a (Foo());
Is free to do 0, 1, or 2 copy constructors:
2 - In function Foo(), A a
creates an A
. When it tries to return, it copies the A
into the return value; the resulting initialization A a(Foo());
copies the result of Foo()
into a new A
.
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 of Foo
directly becomes the A
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.