Search code examples
c++visual-c++return-value-optimization

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?


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.