[Interest] Warning about QHash keys().toVector()
Ahmad Samir
a.samirh78 at gmail.com
Thu Jul 8 09:12:18 CEST 2021
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). What's more efficient is to
iterate right over the QHash itself, and use iterator.key() to fill the vector.
[...]
--
Ahmad Samir
More information about the Interest
mailing list