Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Does try_emplace guarantee to not move the key when not emplaced?

When using a std::map or std::unordered_map:

auto [_, emplaced] = map.try_emplace(std::move(key), std::move(value));

if (!emplaced) {
  // can I safely use key here?
}

cppreference says "these functions do not move from rvalue arguments" but this could be interpreted as meaning only the value arguments based on the context.

I tested this in godbolt with GCC and verified that they key was not moved.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

But in this context I need to know if the standard guarantees this behavior and I don’t know how to find that out.

>Solution :

The standard states:

Effects: If the map already contains an element whose key is equivalent to k, there is no effect.
Otherwise inserts an object of type value_­type constructed with piecewise_­construct, forward_­as_­tuple(k), forward_­as_­tuple(std​::​forward<Args>(args)...).

Moving from k would be an effect. Thus, that not happening is required by the standard.

But in this context I need to know if the standard guarantees this behavior and I don’t know how to find that out.

If you are confused by the wording on cppreference, have a look at the actual text in the standard. You might have to read very carefully, because the wording is often subtle, but meant exactly as it is stated.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading