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

Kevin André hyperquantum at gmail.com
Mon Jun 14 22:23:41 CEST 2021


On Sun, Jun 13, 2021 at 7:14 PM Thiago Macieira
<thiago.macieira at intel.com> wrote:
>
> On Sunday, 13 June 2021 09:20:31 PDT Kevin André wrote:
> > I have the following piece of code:
> >
> >     QVector<int> CompatibilityInterfaceImpl::getActionIds() const
> >     {
> >         return _actions.keys().toVector();   // _actions is a QHash
> >     }
> >
> > In Qt Creator this generates the following warning:
> >    allocating an unneeded temporary container [clazy-container-anti-pattern]
> >
> > How can I avoid the warning in this case?
>
> Create the QVector container, reserve the proper size, and then iterate over
> the actions hashing table inserting the keys.

That's the "write my own conversion function" option I listed :-)

Since I already had a few existing conversion functions, I opted for
your solution:

    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);
    }


Thanks,

Kevin


More information about the Interest mailing list