2

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.

2
  • 10
    myMap.emplace("Some key", otherData).first->second.modify(); Commented Feb 19, 2015 at 3:45
  • Thank you! emplace looks like it's exactly what I need. Commented Feb 19, 2015 at 3:50

1 Answer 1

6

(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.

Sign up to request clarification or add additional context in comments.

1 Comment

Just to note that MyPODType needs to have a default constructor for emplace() to work.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.