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?
> 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).
Compilers often perform Named Return Value Optimization (NRVO) in such cases, but it is not guaranteed.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With