C++ Logo

sg20

Advanced search

Re: [SG20] A draft paper to fix the range-based for loop to make it teachable

From: Giuseppe D'Angelo <giuseppe.dangelo_at_[hidden]>
Date: Tue, 10 Nov 2020 16:08:24 +0100
Hi,

On 10/11/2020 10:24, Nicolai Josuttis via SG20 wrote:
> for years, I have significant problems to teach the range-based for
> loop, because of the bug that it has undefined behavior when iterating
> over a reference to a temporary.
> Thus, I
> - either have to tell beginners significant constraints in using it
> - or have to teach all the details why it is broken
> including references, lifetime extension, universal references
>
> Attached is a draft paper to fix the problem.
> I welcome all feedback and if you want to be a co-author
> (the more support the paper has the better).

There are a couple of things that I'd like to discuss.

One is if it's worth creating an asymmetry regarding not having similar
lifetime extensions everywhere else -- for instance, everywhere `auto
&&` is used. Maybe fixing this problem calls for some other dedicated
syntax, for instance some attribute to place on top of `auto &&` (or any
reference declaration, really)?

> [[lifetime_extend]] auto && r = ~~~; // *every* temporary created in ~~~ is lifetime extended until end of scope

Then, the definition of the ranged-based for can be ported to this;
and/or one could allow the attribute to also be applied to the for as a
whole, with the implication that it gets applied to the internal
exposition-only variable.


The other is minor and purely educational, and has to do with the (if
you want) "straightforward" definition of a range-based for loop in
terms of a "traditional" for loop. An argument that I sometimes use
towards using the new shiny toys from C++11 and beyond (range-based,
lambdas) is that they are truly zero cost abstractions; they are
*defined* to be exactly like the good ol' C++98 for loops using
iterators, or function objects, just with convenient syntax.

If we give special semantics to the range-based for loop (and only to
that) then this is no longer true, and one risks objections "this thing
has embedded hidden magic => the costs are not clear w.r.t. a non-ranged
loop => I am not going to use it".


Thanks for reading,

-- 
Giuseppe D'Angelo | giuseppe.dangelo_at_[hidden] | Senior Software Engineer
KDAB (France) S.A.S., a KDAB Group company
Tel. France +33 (0)4 90 84 08 53, http://www.kdab.com
KDAB - The Qt, C++ and OpenGL Experts

Received on 2020-11-10 09:08:31