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

Gunnar Roth gunnar.roth at gmx.de
Mon Jun 29 07:57:56 CEST 2015


Hi Prav,
somehow i was too relaxed last time , so i did not catch
1.  you were not using a c++11 range-based for loop, but a standard iterator loop.
2. that qt container have a const overload for begin()/end()
3. that Qt containers have constBegin() not const_begin()
4. that stl (since c++11) uses cbegin()/cend() to be able to get a const_iterator from a non const container, which qt container also have.

Phew thats quite a lot. My bad.

One thing to say is that c++ does only choose a const overload , if the instance is const. so even is you do const_iterator cit = container.begin(); the non const version is called and will detach if container is not const.
The other things to say are already said in http://www.dvratil.cz/2015/06/qt-containers-and-c11-range-based-loops/ <http://www.dvratil.cz/2015/06/qt-containers-and-c11-range-based-loops/>

Kevin Grammar's last words ( well in this linked discussion, not in general ) seem to be right	:
The rule of thumb is:
range_for on STL containers, never no Qt containers (can cause deep copy)
foreach on Qt containers, never on STL containers (will cause deep copy)

What is the same what Kai wrote in his reply to my mail.

So in the end , i not only made a too short, but even a wrong suggestion.

But what if you don’t want to care if  container is form qt or std in your code? Or want to be able to replace one by the other?
Then i suggest to write: for(auto && elem: static_cast<const decltype(container) &>(container)) {}, which looks bit ugly, maybe a constexpr inline function to_const() could 
be added to qt so it could be easier to write. Rationale behind auto && , see http://open-std.org/jtc1/sc22/wg21/docs/papers/2014/n3853.htm <http://open-std.org/jtc1/sc22/wg21/docs/papers/2014/n3853.htm>

Regards,
Gunnar




-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.qt-project.org/pipermail/interest/attachments/20150629/893948e6/attachment.html>


More information about the Interest mailing list