I'm relativly new to C++ and this might be a foolish question but I'm trying to understand rValue and lValue references at the moment and this came to my mind:
Let's say we have a map (which comes from a database or whatever) and we want to copy all values of it to a vector.
void insertItems(std::vector<std::string>& v)
{
std::map<int, std::string> names = loadFromDb();
for (auto& kv : names )
{
v.push_back(std::move(kv.second));
}
}
Is it right to use std::move here? std::string provides an move constructor and (maybe not for string but for larger objects) the move constructor is much faster than the copy constructor. Also we know that we do not use the items of the map somewhere else and they go out of scope as soon as we leave the function. So is my presumption right?
I can't see a contradiction in my thoughts but it's a complicated topic and I'm afraid to miss something. P.S.: I think the question name is not the best. If you have a better one feel free to edit it.
Is it right to use
std::movehere?
If you are sure that you won't access the moved values in the future, yes.
You might also want to use std::vector::reserve to preallocate the required space in v.
v.reserve(v.size() + names.size());
Is it right to use
std::movehere?
Yeah. The code looks fine.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With