[Interest] Q_FOREACH creating copy , was (no subject)

Prav pr12og2 at programist.ru
Sun Jun 28 23:40:29 CEST 2015


Hello Gunnar Roth!

> 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 :-)
It is nice to have such time ... I answered you sharply because you gave sharp and short answer and you did not give any supporting arguments for your suggestion ... now you are giving them. Thanks!


>>  for (Container::const_iterator iter=container.begin(); iter!=container.end(); ++iter) {
> And that could possibly detach. But of course only if container is sharing data.
This is the point ... if we use iterator-based loop there is nothing to detach from (comparing to foreach loop which makes container copy which attaches to shared data).
That it why it is not clear why Koehne Kai warns about detaching in iterator based for-loops which you suggested as a replacement of foreach-loops!


> 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.
Ok ... this makes sense ... and I agree with you that it is more clear for those who read my code (and that is why safer) to write loops the way you suggested here. Laziness of adding "const_" is not good :)

I can also add that ... for containers there is "const-versions" of begin() and end() which returns const_iterator ... so this const-version will be used.
This means that there should not be no detachment if:
  for (Container::const_iterator iter=container.begin(); iter!=container.end(); ++iter)
is used.

Just may be not clear for some people who read the code and could make conclusions like you did.


So as I can understand iterator-based for loop is not less safe to possibility of "container data copy problem" ... or I still missing something?
If I am missing ... may be someone can give code example (which is worth many words)
May be Koehne Kai can add anything?




More information about the Interest mailing list