C++ Performance – Writing Code That Relies on Compiler Optimizations

cperformance

I've been learning some C++, and often have to return large objects from functions that are created within the function. I know there's the pass by reference, return a pointer, and return a reference type solutions, but I've also read that C++ compilers (and the C++ standard) allow for return value optimization, which avoids copying these large objects through memory, thereby saving the time and memory of all of that.

Now, I feel that the syntax is much clearer when the object is explicitly returned by value, and the compiler will generally employ the RVO and make the process more efficient. Is it bad practice to rely on this optimization? It makes the code clearer and more readable for the user, which is extremely important, but should I be wary of assuming the compiler will catch the RVO opportunity?

Is this a micro-optimization, or something I should keep in mind when designing my code?

Best Answer

Employ the least astonishment principle.

Is it you and only ever you who is going to use this code, and are you sure the same you in 3 years is not going to be surprised by what you do?

Then go ahead.

In all other cases, use the standard way; otherwise, you and your colleagues are going to run into hard to find bugs.

For example, my colleague was complaining about my code causing errors. Turns out, he had turned off short-circuit Boolean evaluation in his compiler settings. I nearly slapped him.