skip to content

In C++17, how do std::map::try_emplace and insert_or_assign differ from insert, emplace and operator[] when the key already exists?

level: middleimportance: should knowfreq 40%

answer

  1. added by C++17
  2. no effect on an existing key
  3. arguments not moved from
  4. overwrite and report the bool

basics

~20 s

When the key exists, try_emplace does nothing, leaves its arguments untouched and returns {iterator, false}; insert_or_assign assigns the new value and returns {iterator, false}. insert and emplace also keep the old value, but may already have consumed a moved argument.

solid answer

~40 s

Both arrived in C++17 to close gaps in the older API. `try_emplace(k, args...)` is specified to have **no effect** if a key equivalent to `k` exists; otherwise it constructs the mapped value from `args` in place. Because nothing happens on a hit, a `std::unique_ptr` passed with `std::move` still owns its object afterwards. `insert_or_assign(k, v)` assigns `v` to the existing mapped value or inserts a new element, and returns `pair<iterator, bool>` saying which, without requiring a default-constructible mapped type the way `m[k] = v` does. `insert` and `emplace` keep the existing value too, but the standard does not promise to leave their arguments alone: with libc++ a `std::move`d `unique_ptr` passed to `emplace` was emptied and its object destroyed even though the key existed.

code

cpp · 23 lines
cpp
#include <iostream>
#include <map>
#include <memory>
#include <string>

struct Level { int qty; };

int main() {
    std::map<std::string, std::unique_ptr<Level>> books;
    books.try_emplace("ACME", std::make_unique<Level>(Level{10}));

    auto incoming = std::make_unique<Level>(Level{99});
    auto [it, inserted] = books.try_emplace("ACME", std::move(incoming));
    std::cout << "try_emplace inserted=" << inserted
              << " incoming still owns=" << (incoming != nullptr) << '\n';

    auto [it2, inserted2] = books.insert_or_assign("ACME", std::move(incoming));
    std::cout << "insert_or_assign inserted=" << inserted2
              << " qty=" << it2->second->qty << '\n';

    auto [it3, inserted3] = books.insert({"ACME", std::make_unique<Level>(Level{1})});
    std::cout << "insert inserted=" << inserted3 << " qty=" << it3->second->qty << '\n';
}

go deeper

for a junior

Remember that insert and emplace keep the existing value, while assigning through operator[] overwrites it.

for a middle

Explain try_emplace's no-effect guarantee on a hit, insert_or_assign's assign-or-insert result, and why both avoid the default construction operator[] needs.

for a senior

Spot code that loses a move-only value through emplace or insert on an existing key, and rewrite it with try_emplace while keeping one lookup.

for a principal

Set a team default for map insertion: try_emplace for insert-if-absent, insert_or_assign for upserts, operator[] reserved for accumulation.

## Five ways to put a value into a std::map Before C++17, `std::map` offered `operator[]`, `insert` and `emplace`, and each had a corner where it did the wrong thing for some code. C++17 added two members, **`try_emplace`** and **`insert_or_assign`**, to `std::map` and `std::unordered_map` (feature-test macros `__cpp_lib_map_try_emplace` and `__cpp_lib_unordered_map_try_emplace`). Their behaviour when the key **already exists** is what tells them apart: | Call | Key absent | Key present | Returns | |---|---|---|---| | `m[k] = v` | value-initializes, then assigns | assigns | `T&` | | `m.insert({k, v})` | inserts | keeps old value | `pair<iterator, bool>` | | `m.emplace(k, args...)` | constructs in place | keeps old value; arguments may be consumed | `pair<iterator, bool>` | | `m.try_emplace(k, args...)` | constructs value from `args` in place | **no effect**; arguments untouched | `pair<iterator, bool>` | | `m.insert_or_assign(k, v)` | constructs from `k`, `v` | **assigns** `v` to the value | `pair<iterator, bool>` | `insert`, `try_emplace` and `insert_or_assign` also have overloads taking a `const_iterator` hint, `emplace` has `emplace_hint`, and those hinted forms return just an `iterator`; `operator[]` has none. ## The moved-from argument problem The standard specifies `try_emplace` precisely: if the map already contains an element whose key is equivalent to `k`, *there is no effect*. Otherwise it constructs the value with `piecewise_construct`, `forward_as_tuple(k)` and `forward_as_tuple(std::forward<Args>(args)...)`. The key is used for the lookup first, and the mapped arguments are only forwarded when insertion happens. `emplace` has no such promise. It may build a node from its arguments, then discover the key is present and destroy the node. With a move-only value that is a silent loss: - A run with Apple clang 21 and libc++ called `m.emplace("A", std::move(p))` on a map that already held `"A"`. Afterwards `p` was null, and the object it owned had been destroyed. - The same happened with `emplace(std::piecewise_construct, ...)` and with `insert(std::make_pair(key, std::move(r)))`: in the last case the pair is built, and `r` moved from, before `insert` is even called. - `try_emplace("A", std::move(q))` left `q` owning its object. That run shows one implementation; the guarantee to rely on is the one the standard writes for `try_emplace`. ## insert_or_assign versus operator[] `m[k] = v` does two operations: it value-initializes a mapped value if `k` is missing, then assigns. That needs a default constructor, wastes a construction for expensive types, and hides whether anything was inserted. `insert_or_assign`: 1. requires only that `mapped_type&` is assignable from the argument (a *Mandates* clause) and constructible from it for the insert case; 2. constructs directly from the argument when the key is new; 3. returns `{iterator, true}` on insertion and `{iterator, false}` on assignment, which callers often need for logging or metrics. ## A reference-data cache Picture a per-symbol cache of `std::unique_ptr<Level>` in a market-data feed: - When a snapshot arrives that should never replace live state, `try_emplace(symbol, std::move(level))` inserts only for new symbols; on a hit you still own `level` and can reuse or discard it deliberately. - When an update must overwrite, `insert_or_assign(symbol, std::move(level))` replaces the pointer and tells you whether the symbol was new. - When you need the old value back, neither is enough: use `find` and assign through the iterator. ## Hints and complexity All of these are **logarithmic** in `size()`. The hint overloads become amortized constant when the element is inserted right before the hint, which matters when loading already-sorted data. A hint is only advice: a wrong hint costs a normal lookup, not correctness. None of these operations invalidates iterators or references to other elements, because insertion into a node-based tree only relinks pointers. ## Reading the result The non-hinted forms all return `std::pair<iterator, bool>`, which C++17 structured bindings unpack directly: `auto [it, inserted] = m.try_emplace(k, v);`. The iterator always points at the element that now holds key `k`, whether it was just created or was already there, so a single call both inserts and gives you access: - `inserted == true`: the element is new and was built from your arguments. - `inserted == false`: `it->second` is the old value; for `try_emplace` your arguments are untouched, for `insert_or_assign` the value has just been overwritten. That one lookup replaces the common `find`, then `insert` on a miss, pattern, which searches the tree twice. ## Choosing - Insert only if absent, and keep your argument intact on a hit: **`try_emplace`**. - Upsert and know which happened: **`insert_or_assign`**. - Counting or accumulating into a default value: **`operator[]`**. - Inserting a ready-made `value_type`: **`insert`**.

  • Why is m.insert(std::make_pair(k, std::move(ptr))) unsafe for keeping ptr when k may already exist?
    The pair is constructed before `insert` runs, so `ptr` has already been moved into the temporary. If `k` exists, `insert` returns `false` and the temporary, with the object it now owns, is destroyed at the end of the full expression. `try_emplace(k, std::move(ptr))` avoids this because it forwards the argument only when it actually inserts.
  • How does the hint overload of try_emplace change its cost and return type?
    `try_emplace(hint, k, args...)` returns only an `iterator`, because there is no `bool` in the hinted forms. Its complexity matches `emplace_hint`: logarithmic in general, amortized constant when the new element goes immediately before `hint`. It is useful when inserting keys in sorted order, passing `end()` or the previous result as the hint.

  • try_emplace overwrites the value when the key already exists
  • emplace never touches its arguments if the key is already present
  • insert_or_assign needs a default-constructible mapped type
  • m[k] = v tells you whether k was newly inserted
  • try_emplace and insert_or_assign arrived in C++11