Cant compiler decide do if use of move shall be performed for simple cases, does any do it already?
Even with only void setData(std::string arg);
, the compiler will move values like temporaries automatically:
x.setData(my_string + "more"); // move from temporary std::string
x.setData(get_a_string()); // move returned-by-value string
As for the utility of having a &&
-overload, consider some calling code:
std::string q = get_a_string();
myObj.setData(std::move(q));
q = pick_a_string_to_copy[rand() % 10];
Here, if there's only a setData(std::string s)
overload, then the the move constructor for s
will take ownership of q
, and any efficient implementation will leave q
without any pointer to dynamically allocated free-store. Then setData()
will presumably assign to the data member, which will swap with s
's free-store buffer, and s
will delete[]
as setData
returns. The next q =
line above will need to allocate a new buffer for its next value (assuming size()
greater than any short-string optimisation buffer).
This contrasts with the situation if there's a setData(std::string&& s)
overload, where ultimately q
's buffer is likely to be swapped with myobj
's data member's buffer, such that q
still owns dynamic memory that might just be enough to store the next value it's assigned - saving a little time. On the other hand the buffer might be bigger than needed, hogging memory for longer than needed.
Put simply, with &&
the caller can trade free-store buffers rather than losing a buffer or doing inefficient copying.
All up, the functional differences aren't often relevant, but they do exist.