简体   繁体   中英

C++ copy map to vector with std::move

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. PS: 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::move here?

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::move here?

Yeah. The code looks fine.

In the case you show then yes moving will be fine as you won't use the map or its values later.

If the map wasn't a value (like if it was a reference), or you need to use the values in it later, then it's wrong.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM