问题
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?
回答1:
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.
来源:https://stackoverflow.com/questions/11730354/why-is-visual-c-not-performing-return-value-optimization-on-the-most-trivial-c