[Development] QStringLiteral vs QLatin1String , foreach vs for range

Knoll Lars Lars.Knoll at theqtcompany.com
Wed Jan 20 08:18:51 CET 2016


On 20/01/16 08:12, "Development on behalf of André Somers" <development-bounces at qt-project.org on behalf of andre at familiesomers.nl> wrote:



>
>
>Op 20/01/2016 om 06:47 schreef Thiago Macieira:
>> 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.
>Where is this qAsConst coming from? When was it introduced? Where is it 
>documented?
>
>I can't find it in my Qt documentation.

It just got added some weeks ago, after we realised that range-for would lead to our containers detaching. So it'll be in 5.7.

In general, I'm very much in favour of getting rid of foreach in favour of range-for.

Cheers,
Lars



More information about the Development mailing list