QMultiHash::find - prevent detaching shared null

Do not detach when find(key, value) is called on an empty QMultiHash.

As a drive-by: fix return value for QMultiHash::remove() in case of
empty QMultiHash.

Task-number: QTBUG-91736
Pick-to: 6.2 6.1
Change-Id: I1e32f359e7ee9ce8403dae79d02e0b88a20ec4a5
Reviewed-by: Edward Welbourne <edward.welbourne@qt.io>
Reviewed-by: Lars Knoll <lars.knoll@qt.io>
This commit is contained in:
Ivan Solovev 2021-07-07 14:51:36 +02:00
parent 0ac8722d25
commit 82499f8147
2 changed files with 18 additions and 1 deletions

View File

@ -1782,7 +1782,7 @@ public:
qsizetype remove(const Key &key, const T &value) qsizetype remove(const Key &key, const T &value)
{ {
if (isEmpty()) // prevents detaching shared null if (isEmpty()) // prevents detaching shared null
return false; return 0;
detach(); detach();
auto it = d->find(key); auto it = d->find(key);
@ -1844,6 +1844,8 @@ public:
iterator find(const Key &key, const T &value) iterator find(const Key &key, const T &value)
{ {
if (isEmpty())
return end();
detach(); detach();
auto it = constFind(key, value); auto it = constFind(key, value);
return iterator(it.i, it.e); return iterator(it.i, it.e);

View File

@ -668,12 +668,17 @@ void tst_QHash::empty()
//copied from tst_QMap //copied from tst_QMap
void tst_QHash::find() void tst_QHash::find()
{ {
const QHash<int, QString> constEmptyHash;
QVERIFY(constEmptyHash.find(1) == constEmptyHash.end());
QVERIFY(!constEmptyHash.isDetached());
QHash<int, QString> map1; QHash<int, QString> map1;
QString testString="Teststring %0"; QString testString="Teststring %0";
QString compareString; QString compareString;
int i,count=0; int i,count=0;
QVERIFY(map1.find(1) == map1.end()); QVERIFY(map1.find(1) == map1.end());
QVERIFY(!map1.isDetached());
map1.insert(1,"Mensch"); map1.insert(1,"Mensch");
map1.insert(1,"Mayer"); map1.insert(1,"Mayer");
@ -682,6 +687,16 @@ void tst_QHash::find()
QCOMPARE(map1.find(1).value(), QLatin1String("Mayer")); QCOMPARE(map1.find(1).value(), QLatin1String("Mayer"));
QCOMPARE(map1.find(2).value(), QLatin1String("Hej")); QCOMPARE(map1.find(2).value(), QLatin1String("Hej"));
const QMultiHash<int, QString> constEmptyMultiHash;
QVERIFY(constEmptyMultiHash.find(1) == constEmptyMultiHash.cend());
QVERIFY(constEmptyMultiHash.find(1, "value") == constEmptyMultiHash.cend());
QVERIFY(!constEmptyMultiHash.isDetached());
QMultiHash<int, QString> emptyMultiHash;
QVERIFY(emptyMultiHash.find(1) == emptyMultiHash.end());
QVERIFY(emptyMultiHash.find(1, "value") == emptyMultiHash.end());
QVERIFY(!emptyMultiHash.isDetached());
QMultiHash<int, QString> multiMap(map1); QMultiHash<int, QString> multiMap(map1);
for (i = 3; i < 10; ++i) { for (i = 3; i < 10; ++i) {
compareString = testString.arg(i); compareString = testString.arg(i);