[Interest] Q_FOREACH creating copy , was (no subject)
Gunnar Roth
gunnar.roth at gmx.de
Sun Jun 28 19:54:47 CEST 2015
Hi Prav.
Originally i planned to not answer to you anymore, but well its such a sunny day here and i am sitting lazily an my balcony and are in a really good mood now :-)
> Am 28.06.2015 um 19:28 schrieb Prav <pr12og2 at programist.ru>:
>
>> When a container calls detach(), it means it is no longer attached to the
>> container it was copied from (if it was copied)
> OK, thanks ... this clarify what detach means copying of container.
>
> But I still can not get additional danger in using iterator-base loops:
>
> Gunnar Roth - I woud suggest to not use QFOREACH, use c++11 range-based for loop.
>
> Koehne Kai - I'd be careful with such an advice, unless you understand the performance
> implications (because range-based loop will sometimes detach the Qt Container)
>
> I can only imagine that Koehne Kai forgot what we are talking about ...
>
> For things like:
>
> typedef int Item; //Select any type you like here
> typedef QVector<Item> Container; //Select any container you like here
>
> Container container;
> <<fill-container-code>>
>
>
> Gunnar Roth is suggesting instead of:
> foreach(const auto &item, container) {
> <<loop-code>>
> }
>
>
> use:
> for (Container::const_iterator iter=container.begin(); iter!=container.end(); ++iter) {
> const Item &item=*iter;
>
> <<loop-code>> // the same as in previous loop
> }
>
And that could possibly detach. But of course only if container is sharing data. As you use begin() and not const_being() and begin returns an non-const iterator. It doesn’t matter that you assign
this to a const_iterator in the end. begin() needs to detach , meaning abandoning the reference to the original Container and copying the date ( copy on write) , if such exists.
If you use
for (Container::const_iterator iter=container.const_begin(); iter!=container.const_end(); ++iter)
no detach will happen as const_begin only return a const_iterator , which you cannot use to modify the container data.
> And how it is possible to detach something in the last example? I do not even see what to detach from what here?
>
> So Koehne Kai's remark seems strange for me.
>
I may seem, but he is completely correct, i just did not make may point completely clear.
Regards,
Gunnar
More information about the Interest
mailing list