From 0375757bfb3852ace3bf3237a7de0ed2dbb371d8 Mon Sep 17 00:00:00 2001 From: Lars Knoll Date: Fri, 7 Feb 2020 12:29:59 +0100 Subject: Implement emplace() for QHash and QMultiHash MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit At the same time use the opportunity to refactor the insertion code inside the implementation of QHash to avoid copy and move constructors as much as possible and always construct nodes in place. Change-Id: I951b4cf2c77a17f7db825c6a776aae38c2662d23 Reviewed-by: MÃ¥rten Nordheim --- src/corelib/tools/qcache.h | 18 ++++++++++++++---- 1 file changed, 14 insertions(+), 4 deletions(-) (limited to 'src/corelib/tools/qcache.h') diff --git a/src/corelib/tools/qcache.h b/src/corelib/tools/qcache.h index f043ea9cff..3582a44e32 100644 --- a/src/corelib/tools/qcache.h +++ b/src/corelib/tools/qcache.h @@ -99,9 +99,13 @@ class QCache value(std::move(t)) { } - static Node create(Key &&k, Value &&t) noexcept(std::is_nothrow_move_assignable_v && std::is_nothrow_move_assignable_v) + static void createInPlace(Node *n, const Key &k, T *o, int cost) { - return Node(std::move(k), std::move(t)); + new (n) Node{ Key(k), Value(o, cost) }; + } + void emplace(T *o, int cost) + { + value = Value(o, cost); } static Node create(const Key &k, Value &&t) noexcept(std::is_nothrow_move_assignable_v && std::is_nothrow_move_assignable_v) { @@ -230,9 +234,15 @@ public: return false; } trim(mx - cost); - auto it = d.insert(Node::create(Key(key), Value(object, cost))); + auto result = d.findOrInsert(key); + Node *n = result.it.node(); + if (result.initialized) { + cost -= n->value.cost; + result.it.node()->emplace(object, cost); + } else { + Node::createInPlace(n, key, object, cost); + } total += cost; - Node *n = it.node(); n->prev = &chain; n->next = chain.next; chain.next->prev = n; -- cgit v1.2.3