Search code examples
c++c++11movemove-semantics

Would Move Semantic in C++ 11 be executed if there is no rvalue parameter with function signature?


To make program run more efficiently, move semantic is introduced since C++ 11, for example:

void fun(const string& str); //1st
void fun(string&& str); //2nd since c++ 11

If I use it like fun("tmpStr");, the 2nd function signatured with rvalue would be used,and it is more efficient than the 1st function.

But the problem is that if I need ONLY 1 function signature to handle paramters with both lvalue and rvalue, what shoud I do?

  1. if the 1st one is kept, it is not efficient with rvalue;
  2. if the 2nd one is kept, it is efficient with rvalue, but I have to fun(std::move(lvalue)) to make it possible with lvalue, which I think the added codes std::move looks like redundant---moreover, this makes the status of lvalue undefined after this function.

With the thought above, I wonder if Move Semantic in C++ 11 would be executed if there is no rvalue parameter with function signature like the 1st one, even just in release(optimized) mode? if the answer is not , then what is the reason behind it?


Solution

  • Move semantics is irrelevant in this case because you don't want to modify the argument.

    "tmpStr" is not a std::string, it is a const char*. Since you are taking a non-(const lvalue) reference to std::string, the compiler has to create a std::string somewhere. Allocation overhead is already incurred. Then, which reference you use really doesn't matter if you don't modify the temporary string. The best way to write the function is:

    void fun(std::string_view sv)
    

    This automatically handles string literals and std::strings, etc., and incurs zero allocation overhead. This is more efficient than moving. No move semantics involved.