Question

Does Visual C++ not perform return-value optimization?

#include <cstdio>
struct Foo { ~Foo() { printf("Destructing...\n"); } };
Foo foo() { return Foo(); }
int main() { foo(); }

I compile and run it:

cl /O2 test.cpp
test.exe

And it prints:

Destructing...
Destructing...

Why is it not performing RVO?

Was it helpful?

Solution

When I test with this:

#include <iostream>
struct Foo { 
    Foo(Foo const &r) { std::cout << "Copying...\n"; }
    ~Foo() { std::cout << "Destructing...\n"; }
    Foo() {}
};

Foo foo() { return Foo(); }

int main() { Foo f = foo(); }

...the output I get is:

Destructing...

No invocation of the copy constructor, and only one of the destructor.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top