[llvm] MapVector: add C++17-style try_emplace and insert_or_assign (PR #71969)
Fangrui Song via llvm-commits
llvm-commits at lists.llvm.org
Fri Nov 10 12:07:13 PST 2023
================
@@ -114,31 +114,56 @@ class MapVector {
return Pos == Map.end()? ValueT() : Vector[Pos->second].second;
}
- std::pair<iterator, bool> insert(const std::pair<KeyT, ValueT> &KV) {
- std::pair<KeyT, typename MapType::mapped_type> Pair = std::make_pair(KV.first, 0);
- std::pair<typename MapType::iterator, bool> Result = Map.insert(Pair);
+ template <typename... Ts>
+ std::pair<iterator, bool> try_emplace(const KeyT &Key, Ts &&...Args) {
+ std::pair<typename MapType::iterator, bool> Result =
+ Map.insert(std::make_pair(Key, 0));
auto &I = Result.first->second;
if (Result.second) {
- Vector.push_back(std::make_pair(KV.first, KV.second));
+ Vector.emplace_back(std::piecewise_construct, std::forward_as_tuple(Key),
+ std::forward_as_tuple(std::forward<Ts>(Args)...));
I = Vector.size() - 1;
return std::make_pair(std::prev(end()), true);
}
return std::make_pair(begin() + I, false);
}
-
- std::pair<iterator, bool> insert(std::pair<KeyT, ValueT> &&KV) {
- // Copy KV.first into the map, then move it into the vector.
- std::pair<KeyT, typename MapType::mapped_type> Pair = std::make_pair(KV.first, 0);
- std::pair<typename MapType::iterator, bool> Result = Map.insert(Pair);
+ template <typename... Ts>
+ std::pair<iterator, bool> try_emplace(KeyT &&Key, Ts &&...Args) {
+ std::pair<typename MapType::iterator, bool> Result =
+ Map.insert(std::make_pair(Key, 0));
----------------
MaskRay wrote:
If we use `std::move` here, `std::forward_as_tuple(static_cast<KeyT &&>(Key)),` below may referenced a moved-out `Key`.
An alternative is to use
```
Map.insert(std::make_pair(std::move(Key), 0)); // map insertion
...
std::forward_as_tuple(Result.first->first) // vector insertion
```
but this does not save copy/move numbers.
https://github.com/llvm/llvm-project/pull/71969
More information about the llvm-commits
mailing list