Consider this function:
std::string
myClass::myFunction2() {
std::string result = myClass::myFunction1();
return result;
}
I'm hoping that the compile performs return value optimization. How can I make sure this actually happens, and the code will not copy the result redundantly?
In the context of the C++ programming language, return value optimization (RVO) is a compiler optimization that involves eliminating the temporary object created to hold a function's return value. RVO is allowed to change the observable behaviour of the resulting program by the C++ standard.
(Named) Return value optimization is a common form of copy elision. It refers to the situation where an object returned by value from a method has its copy elided. The example set forth in the standard illustrates named return value optimization, since the object is named.
> 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).
RVO is always applied, if possible. For your case, assuming myFunction1() does not return different named objects depending on the path of execution, the compiler should perform RVO. If it returns different named objects with different execution path, then the compiler is not able to perform optimization.
I recommend to do your own experiments:
To disable optimization everywhere, use pragmas:
#pragma GCC push_options
#pragma GCC optimize (ARG)
//your code
#pragma GCC pop_options
To disable optimization for a specific function, use __attribute__(()):
void __attribute__((optimize(ARG))) foo(unsigned char data) {
// your code
}
ARG can either be numbers (i.e. an optimization level) or strings starting with 0 (i.e. an optimization option) and etc. For what you need, you can substitute ARG with "O0" Then run the both versions of your code using gcc -S to see the difference. I recommend you to read gcc 4.4 or newer doc.
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