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 18:40:32 +0100
On 10/11/2020 18:23, Arthur O'Dwyer via SG20 wrote:
>
> So the teacher will still have to explain why [a] has UB but [c] doesn't.
> So making [b] behave like [c] instead of [a] doesn't really make C++
> more /teachable/, IMO.
> But it does fix a potential source of dangling-reference bugs, for
> basically zero mental cost. I like it.

Well, one could also build counter-examples.

Something along the lines of

> std::unique_lock lock(some_mutex);
> for (whatever ; getObject(id).getName()) ~~~; // WORKS with the proposed change
> lock.unlock();

Then one realizes, wait a minute, I don't need to keep the lock for the
whole loop, only when getting the object, let me rewrite it

> std::unique_lock lock(some_mutex);
> auto && x = getObject(id).getName(); // auto && "because it's what for does"
> lock.unlock();
> for (whatever ; x) ~~~; // Does not work any more

So the mental cost is *somehow* still there...?

Thanks,
-- 
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 11:40:39