try_emplace
can indeed replace most uses of emplace
, but if you have an unusual use case of a map
with a non-copyable and immovable key type, try_emplace
will not work because it copies or moves the key. In that case, you must use emplace
with std::pair
‘s piecewise construction constructor to avoid copies and moves.
Even if your key type is copyable and/or moveable, piecewise construction is the only way to avoid copy or move constructing the key, so there might be cases when you prefer that over try_emplace
.