Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do C++11 compilers turn local variables into rvalues when they can during code optimization?

Sometimes it's wise to split complicated or long expressions into multiple steps, for example (the 2nd version isn't more clear, but it's just an example):

return object1(object2(object3(x))); 

can be written as:

object3 a(x); object2 b(a); object1 c(b); return c; 

Assuming all 3 classes implement constructors that take rvalue as a parameter, the first version might be faster, because temporary objects are passed and can be moved. I'm assuming that in the 2nd version, the local variables are considered to be lvalues. But if the variables aren't later used, do C++11 compilers optimize the code so the variables are considered to be rvalues and both versions work exactly the same? I'm mostly interested in Visual Studio 2013's C++ compiler, but I'm also happy know how the GCC compiler behaves in this matter.

Thanks, Michal

like image 940
Michał Fronczyk Avatar asked Feb 17 '14 13:02

Michał Fronczyk


People also ask

How does a compiler optimize code?

Compiler optimization is generally implemented using a sequence of optimizing transformations, algorithms which take a program and transform it to produce a semantically equivalent output program that uses fewer resources or executes faster.

How does the C++ compiler optimize?

The C/C++ compiler compiles each source file separately and produces the corresponding object file. This means the compiler can only apply optimizations on a single source file rather than on the whole program. However, some important optimizations can be performed only by looking at the whole program.


2 Answers

The compiler cannot break the "as-if" rule in this case. But you can use std::move to achieve the desired effect:

object3 a(x); object2 b(std::move(a)); object1 c(std::move(b)); return c; 
like image 61
juanchopanza Avatar answered Oct 17 '22 09:10

juanchopanza


As juanchopanza said, the compiler cannot (at C++ level) violate the "as-if" rule; that is all transformations should produce a semantically equivalent code.

However, beyond the C++ level, when the code is optimized, further opportunities may arise.

As such, it really depends on the objects themselves: if the move-constructors/destructors have side effects, and (de)allocating memory is a side effect, then the optimization cannot occur. If you use only PODs, with default move-constructors/destructors, then it will probably be automatically optimized.

like image 42
Matthieu M. Avatar answered Oct 17 '22 09:10

Matthieu M.