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?
EDIT 1 (example of how 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)
?
emplace_back
, because it seems like and important use case. If I have a function call returning a value, and I want to store it in an array, how to I ensure the objects are instantiated straight inside the array?vec.emplace_back(mkobj());
? `obj&& o=mkobj(); vec.emplace_bac(std::move(o))``? When is it even necessary, an when can I be sure it will be optimized already?