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