[Development] QStringLiteral vs QLatin1String , foreach vs for range
Thiago Macieira
thiago.macieira at intel.com
Wed Jan 20 06:47:38 CET 2016
On Wednesday 20 January 2016 05:20:36 Kevin Kofler wrote:
> Thiago Macieira wrote:
> > foreach copies; ranged for doesn't.
>
> … unless you try to use it on a non-const Qt container with usage count >1,
> then it will even deep-copy (detach) it! (I know you know this, but you
> should warn people about it.) So you need to be very careful about what you
> pass to ranged for.
Indeed.
But his is the argument that convinced me: with foreach and Qt containers, you
usually get the runtime performance you want, but it costs in dead code since
the deep-copy code will be present (at least until we can get rid of the
unsharable flag). With ranged for plus qAsConst, there's no copy code
generated.
So instead of:
foreach (auto x, container)
You'll write:
for (auto x : qAsConst(container))
or if you know it's already const, you can skip the qAsConst part.
This is no more and no less readable, but is more explicit about what it does.
--
Thiago Macieira - thiago.macieira (AT) intel.com
Software Architect - Intel Open Source Technology Center
More information about the Development
mailing list