Question

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.

Était-ce utile?

La solution

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.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top