2

Let's consider the following functions:

void processString1(const string & str) { /** **/}
void processString2(string && str) { /** **/}

processString1("Hello");
processString2("Hello");

As I assume, processString1 will invoke copy constructor and processString2 a move constructor of string. What is more efficient?

michalt38
  • 1,193
  • 8
  • 17

1 Answers1

3

Your understanding is misguided here.

First, neither of those functions take a value - they both take a reference. So, when an object is passed to either one, no constructor is called - whatever object is passed is simply bound to a reference.

However, your function calls pass a C-string - and there is an implicit conversion from a C-string to a std::string.

Thus, each one will construct a TEMPORARY std::string our of the C-string "Hello".

That temporary object will bind to a reference-to-const in the first case and a rval-reference-to-non-const in the second case.

The language guarantees that the lifetime of the temporary will exist for at least the lifetime of the function call.

Neither function call does any construction - the only construction happens when the C-string is implicitly converted to an instance of std::string.

Jody Hagins
  • 27,943
  • 6
  • 58
  • 87