Is there any reason to use std::map::emplace() instead of try_emplace() in C++1z?

前端 未结 3 445
北荒
北荒 2020-12-29 18:50

In C++17, std::map and std::unordered_map got a new member-function template: try_emplace(). This new addition, proposed in n4279, behaves similarly to emplace(), but has th

3条回答
  •  不知归路
    2020-12-29 19:13

    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.

提交回复
热议问题