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

André Pönitz apoenitz at t-online.de
Sun Jun 13 22:34:46 CEST 2021


On Sun, Jun 13, 2021 at 06:20:31PM +0200, Kevin André wrote:
> Hi,
> 
> 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?
> 
> I am using Qt 5.12, so I return a QVector instead of a QList because
> using the old (Qt 5) QList is discouraged. Unfortunately many Qt API's
> still use QList for nearly everything, so I am faced with a difficult
> choice:
> 
>   1) go back to using QList

That would be my advice.

While QList never was the atrocity some people wanted us to believe [1],
you actually have one of the rare cases here were Q(5)Vector really
takes less memory than Q(5)List on 64bit machines, roughly 4 bytes
times the number of items in your _actions container.

But given that your application is apparently fine with using QHash::keys
here it is safe to say that you will not observe any difference.

Andre'

[1] https://lists.qt-project.org/pipermail/development/attachments/20200425/8b0cca64/attachment.mht


More information about the Interest mailing list