There is one main.cpp file, in which two global functions getSomeResultFromSomeFunc (), processResult () and the function main () are defined:

std::string getSomeResultFromSomeFunc() { std::string result; if ( cond1 ) { // result = ... } else if ( cond2 ) { // result = ... } return result; } void processResult( const std::string& result ) { ... } int main(void) { std::string myResult = std::move( getSomeResultFromSomeFunc() ); processResult( myResult ); return 0; } 

Should I use std :: move () when creating a myResult object from another object that is returned by a function? To call the move constructor for the myResult object instead of the copy constructor, since this is a faster way to create an object? Or will the compiler automatically call a relocation constructor instead of a copy constructor, and using std :: move is redundant? And therefore it is enough to write easier?

 std::string myResult = getSomeResultFromSomeFunc(); 

or

 std::string myResult( getSomeResultFromSomeFunc() ); 

For user-defined types, it is easy to check how the compiler behaves, but for types from std, there is no way to check?

Are there differences in the use of std :: move for C ++ 0x and C ++ 11 in this case?

  • one
    In fact, when you call, the internal variable result will not be created de facto - immediately myResult will be used. No move is needed in principle. - Harry
  • one
    Oh, by the way, what do you mean by C ++ 0x? C ++ 03? so there was no semantics of moving (and move respectively) in it. - Harry
  • Yes, move is not needed. С ++ 0x - a trimmed version of С ++ 11, which can be used for Centos 6.x - Ankallar-Don

1 answer 1

The result returned by the function in your example is prvalue. There is no point in applying std::move it.

With your std::move you would rather force the compiler to perform a temporary materialization conversion where there was no need for it, and also suppress the optimization (return value optimizations - RVO), artificially “tearing off” the initialized myResult object from its initializer result .

In the best case, a successful RVO in your code will neither move nor copy - the result of the function will be constructed right in your myResult .

Please note: https://godbolt.org/z/_4tnNh
The getSomeResultFromSomeFunc function immediately receives the recipient's address ( myResult ) in the rdi register as rdi and conducts all further work directly with myResult . No local result is created at all and no copying / moving of the result is performed.