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

只谈情不闲聊 提交于 2020-01-01 04:17:05

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!