I have a function of the form void foo(std::string str);
I want to use it in two scenarios:
send a copy of the original value to it:
std::string myString = "any data that I want to keep in its original state"
foo(myString);
pass it the original value using std::move
:
std::string myString = "any data that I don't need anymore"
foo(std::move(myString));
Is it ok to send a value to the lvalue argument using std::move?
Yes it's OK here.
foo
is accepting its parameter by value, so it has to be constructed somehow.
In your 1st case, the str
parameter is copy-constructed from the passed argument.
In your 2nd case (with the std::move
), the str
parameter is move-constructed from the passed argument (this will leave the moved-from myString
in a valid but unspecified state).
A side note:
Using a by value parameter to support both copy and move is quite a common idiom.
One example is implementing an assignment operator with a by value parameter together with the copy-and-swap idiom.
See some more info here: What is the copy-and-swap idiom?.