C++17 feature proposal: Allow std::map::try_emplace and std::map::insert_or_assign

233 views
Skip to first unread message

Daniel Cheng

unread,
Jan 6, 2022, 3:10:58 PM1/6/22
to cxx
try_emplace():
Unlike emplace(), try_emplace() doesn't move from its arguments if the key is already present.

We should probably recommend try_emplace() over emplace(), though I wouldn't advocate for a bulk replacement.

There's also a (recent) internal C++ TotW that recommends insert({key, value}) in most instances over try_emplace(). This was news to me.

insert_or_assign():
Like std::map::operator[], but does not require the value type be default constructible.

It has a return type like that of insert() - it returns an iterator and a bool whether or not the insertion occurred.

In most cases, operator[] is simpler and good enough, but we should allow insert_or_assign() where it's useful.

Assuming there are no objections to using either of these, we would also remove the existing base::TryEmplace() and base::InsertOrAssign() helpers. This would also give us a consistent API between base::flat_map (which already implements these helpers) and std::map and (eventually) Abseil's swisstables.

Separately, does anyone know the process of making internal TotW's public? Is there a reason to disagree with the guidance to prefer insert() to emplace() for maps? https://abseil.io/tips/112 already hinted at this, but only mentioned vectors and sets, so I had actually been recommending emplace for maps until recently :)

Daniel

Peter Kasting

unread,
Jan 6, 2022, 3:18:00 PM1/6/22
to Daniel Cheng, cxx
+1

PK

--
You received this message because you are subscribed to the Google Groups "cxx" group.
To unsubscribe from this group and stop receiving emails from it, send an email to cxx+uns...@chromium.org.
To view this discussion on the web visit https://groups.google.com/a/chromium.org/d/msgid/cxx/CAF3XrKoUDwOUMEKm%2BKkQNzQDbRYDaLvuByv6%3DSB6a1iYBiLjSQ%40mail.gmail.com.

dan...@chromium.org

unread,
Jan 6, 2022, 4:15:20 PM1/6/22
to Peter Kasting, Daniel Cheng, cxx
+1 on using them, the guidance (add to Do's And Don'ts?) and removing the base helpers

Jeremy Roman

unread,
Jan 6, 2022, 4:16:11 PM1/6/22
to dan...@chromium.org, Peter Kasting, Daniel Cheng, cxx
+1; these are reasonable and have no real downsides in Chromium.

Reply all
Reply to author
Forward
0 new messages