Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if return value optimization happened?

Tags:

c++

gcc

g++

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?

like image 469
Ari Avatar asked Aug 18 '17 21:08

Ari


People also ask

How does return value optimization work?

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.

What is named return value optimization?

(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.

Does C have return value optimization?

> 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).


Video Answer


1 Answers

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.

like image 98
Ali Abbasinasab Avatar answered Nov 15 '22 01:11

Ali Abbasinasab