[Interest] Warning about QHash keys().toVector()

Oliver Knoll till.oliver.knoll at gmail.com
Thu Jul 8 09:31:36 CEST 2021



> Am 08.07.2021 um 09:13 schrieb Ahmad Samir <a.samirh78 at gmail.com>:
> 
> On 08/07/2021 08:41, Oliver Knoll wrote:
>>>    template<typename K, typename V> static QVector<K>
>>> keysToVector(QHash<K,V> const& hash)
>>>    {
>>>        QVector<K> v;
>>>        v.reserve(hash.size());
>>> 
>>>        for (auto it = hash.keyBegin(); it != hash.keyEnd(); ++it)
>>>            v.append(*it);
>>> 
>>>        return v;
>>>    }
>>> 
>>>    QVector<int> CompatibilityInterfaceImpl::getActionIds() const
>>>    {
>>>        return keysToVector(_actions);
>>>    }
>> Dear all,
>> I am sorry to kind of hijack this thread with a follow-up question, but I am trying to better understand what‘s going on „under the C++ hood“, especially given the solution above.
>> When we look at the original code again:
>> QVector<int> CompatibilityInterfaceImpl::getActionIds() const
>>    {
>>        return _actions.keys().toVector();   // _actions is a QHash
>>    }
>> And the warning it generates:
>>   allocating an unneeded temporary container [clazy-container-anti-pattern]
> 
> What clazy is warning about here is the, temporary intermediate, container created by QHash::keys(), this creates a QList of keys (which is then converted to a QVector).

Ah, of course! I totally overlooked the call to keys(), which - yes - creates yet another „temporary“ variable. In fact, that implicitly generated QList /is/ (must be) the „unneeded temporary container“ the warning is referring to.

Somehow I was totally focusing on the call to toVector(), and wrongly thought that this was the „unneeded temporary container“ the warning was referring to. Which totally doesn‘t make any sense… doh!

Thank you very much for your quick and helpful response!

Cheers, Oliver


More information about the Interest mailing list