I haven't read the paper yet (answering from my phone), but I heard you mentioning the problem and your suggested solution for it before (I think it was in a keynote of a conference or maybe in cppcast episode, or both). So I'm sorry if your paper already discussing everything I'm saying below. I promise to read it through later :)

1. I don't think this was discussed before. Thanks for bringing this up.

2. I agree this is an issue, and even range-based for loop with initializer doesn't fully solve it as we still have to be careful when to use the initializer and what part of the expression should be there.

3. IMHO, the best and simplest solution is to use std::ranges::for_each, because it holds the temporary till the end of the loop due to the function call semantics.

On Tue, Nov 10, 2020, 11:25 AM Nicolai Josuttis via SG20 <sg20@lists.isocpp.org> 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).

Please also tell me if you have yourself significant teaching problems
there or interesting war stories about the problem.
There is a surprising number of people who thinks this is not a problem
at all.

May be SG20 can support the paper as a whole,
because IMO we really have to heal C++ to make it teachable again.


Note: So far I was not a member of this email list;
so forgive me if this was discussed before.

Nicolai M. Josuttis
+49 (0)531 / 129 88 86
+49 (0)700 / JOSUTTIS

 C++: http://cppstdlib.com, http://cppstd17.com,
      http://tmplbook.com, http://cppmove.com
 SOA: http://soa-in-practice.com

SG20 mailing list