Drew
Drew

Reputation: 13398

C++ - insert into std::map directly without assignment operator

I have a std::map that I would like to insert an object into, but I would like to avoid unnecessary copies, since it is a large object, and copies take time. I tried this:

MyPODType data(otherData);
data.modify();
myMap["Some key"] = data;

However this requires 2 copies: one to copy the otherData, and one in the assignment operator to insert the object. Since it's POD, the copy constructor and assignment operator are both the default.

How can I do this with only 1 copy? I realize some compilers will optimize out the second copy but I'd like to do this in a portable way.

Upvotes: 2

Views: 1373

Answers (1)

M.M
M.M

Reputation: 141576

(I am assuming MyPODType is the exact value_type of your map)

As pointed out by Igor Tandetnik in comments, since C++11 you can write:

myMap.emplace("Some key", otherData);

and then you can call modify() on the value while it is in the map.

The emplace function will use perfect forwarding to forward your arguments to the constructor of the key and value respectively, instead of having to create a temporary std::pair or default-construct a value.

It's also possible to use insert:

std::pair<KeyType, MyPODType> p = { "Some key ", otherData };
p.second.modify();
myMap.insert( std::move(p) );

although the emplace option seems simpler.

Upvotes: 6

Related Questions