I have the following function inside a class
void add_state(std::string &&st) {
state.emplace_back(st); // state is a vector
}
st
is an l-value (rvalue reference to a string in this case) based on my understanding. If, I want to move st
into the last element in state
, should I be using state.emplace_back(std::move(st))
? What happens if I leave it the way it's written above?
add_state
is called):// do a series of operations to acquire std::string str
add_state(std::move(str));
// also note that str will never be used again after passing it into add_state
Would it be better if I made add_state(std::string &st)
instead? In this case, I think I can just simply call it with add_state(str)
?
[...] should I be using
state.emplace_back(std::move(st))
?
Yes.
What happens if I leave it the way it's written above?
You have correctly identified that st
is an lvalue, so it gets copied.
Would it be better if I made
add_state(std::string &st)
instead? In this case, I think I can just simply call it withadd_state(str)
?
You could, but you shouldn't. std::move
is just type juggling, it does not do anything by itself (in particular, it doesn't move anything). The actual operation happens inside std::string::basic_string(std::string &&)
which is called by emplace_back
after it receives the std::string &&
. Making your own parameter an lvalue reference has no effect other than surprising the caller, who gets their std::string
eaten without an std::move
on their part.