[Qt-creator] C++11 in Creator's source: Update required features
Daniel Teske
Daniel.Teske at theqtcompany.com
Mon Mar 30 17:06:28 CEST 2015
On Monday 09 Mar 2015 12:14:04 Daniel Teske wrote:
> > If anyone wants to propose a coding style, please come forward.
>
> ** Range-based for **
> I'd like to propose the following guideline:
>
> Do not use the C++11 range based for loop unless your loop modifies the
> contents of the container. Prefer to use Qt's foreach macro for read-only
> iteration.
>
>
> Reason:
> The range-based for loop is using the helper functions std::begin() and
> std::end, which unless overloaded call container.begin() and
> container.end().
>
> Which for Qt's container classes call detach unless the container is const.
>
> Overloading std::begin() and std::end() to return const_iterators doesn't
> work, since you can't then no longer modify the container's contents.
>
> Thus, the range-based for loop has worse performance for read-only iteration
> unless:
>
> - The container is const
> - The container is unshared
>
> This makes imho the range-based for loop to error-prone for read-only
> iteration. I'd like to allow the range-based for loop for modification,
> since that's something that simply isn't possible with qt's foreach macro.
>
> But, I would also agree to a coding guideline of discouraging the range
> based for loop completely.
So, we had quite a bit of discussion on how to treat ranged based for loops
internally, and thus I like to suggest a different coding guideline:
Use range based for-loops, but beware of the spurious detachment problem.
If the for-loop only reads the container and it's non-obvious whether the
container is const or unshared, use std::cref() to ensure that the container
isn't unnecessarily detached.
daniel
More information about the Qt-creator
mailing list