The std::map subscript operator ([]) is a convenient but sometimes dangerous feature, as it can create unintended default-constructed entries. By understanding the behavior of various map insertion and lookup methods—such as insert, emplace, try_emplace, and insert_or_assign—developers can write more efficient and predictable code while avoiding unnecessary key-value creations and duplicate lookups.
A Simplified Overview of Ways to Add or Update Elements in a std::map
by Raymond Chen
From the article:
Some time ago, I mentioned how the
std::subscript operator is a dangerous convenience. In that article, I linked to an overview of the insertion emplacement methods, but I’m going to recapture the essential points in a table.¹map In the table below, the discussion of “consumed” or “not consumed” refers to the case that
vis an rvalue reference likestd::.move(something) We can reorganize the table by effect.
Exercise: Why are the bottom left two boxes blank?



Add a Comment
Comments are closed.