When can the compiler not use RVO or NRVO?

Moving semantics can be useful when the compiler cannot use RVO and NRVO . But in this case, the compiler cannot use these functions?

+6
source share
2 answers

The answer is that it depends on the compiler and the situation. For instance. flow control branching may confuse optimizers. Wikipedia give this example:

#include <string> std::string f(bool cond = false) { std::string first("first"); std::string second("second"); // the function may return one of two named objects // depending on its argument. RVO might not be applied return cond ? first : second; } int main() { std::string result = f(); } 
+5
source

Well, it’s not so, whether the compiler can use RVO, but whether it can thereby avoid creating a copy.

Consider:

 struct Blah { int x; Blah( int const _x ): x( _x ) { cout << "Hum de dum " << x << endl; } }; Blah foo() { Blah const a( 1 ); if( fermatWasRight() ) { return Blah( 2 ); } return a; } 

Getting side effects (output from the constructor) right here, at first glance, is quite incompatible with building a directy in the repository provided by the caller. But if the compiler is smart enough, then he may notice that the destruction of this object is zero. And more generally, for a specific situation, if the compiler is smart enough, it may be able to avoid the copy operation, no matter how difficult we are developing the code.

I’m not sure of the formality, although, but with a higher load on the object, so copying will be more expensive, this is one case where the semantics of movement can help, so that optimization will be guaranteed regardless of whether the compiler (or not).

+3
source

Source: https://habr.com/ru/post/915321/


All Articles