Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is Visual C++ not performing return-value optimization on the most trivial code?

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?

like image 395
user541686 Avatar asked Jul 30 '12 22:07

user541686


People also ask

Does C have return value optimization?

> Note also that C doesn't have return-value-optimization, hence all your struct-returning functions will cause a call to memcpy (won't happen when compiled in C++ mode of course).

Is return value optimization guaranteed?

Compilers often perform Named Return Value Optimization (NRVO) in such cases, but it is not guaranteed.


1 Answers

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.

like image 76
Jerry Coffin Avatar answered Oct 10 '22 03:10

Jerry Coffin