How do you safely deal with range.front?

Jonathan M Davis newsgroup.d at jmdavisprog.com
Mon Jan 1 02:18:36 UTC 2018


On Sunday, December 31, 2017 01:03:17 Tony via Digitalmars-d-learn wrote:
> For me, front() should throw a pre-defined exception when called
> on an empty range in order to eliminate undefined behavior. It
> does take some time to make a check, but D does array bounds
> checking by default. Ideally the front() check could be turned
> off somehow ("-boundschecks=off") by the user for those who want
> maximum speed, but I guess there is no way to do that when using
> pre-compiled functions in a library.

Except that the reason for arrays throwing RangeErrors when you try and
index them out-of-bounds is to avoid memory safety issues, which is not
necessarily the case at all when you're talking about ranges. Having ranges
in general be checking empty in front, popFront, back, etc. would add
unnecessary overhead - especially when you consider that ranges often wrap
other ranges. You'd be layering on check after check when the calling code
is already supposed to be checking empty when necessary to make sure that
the range isn't empty. You'd even be layering checks on top of the checks
that arrays already do, since many ranges are ultimately wrapped around a
dynamic array at their core.

The extra checks on arrays avoid nasty memory-related problems and don't
involve layering on extra checks all over the place, whereas ranges in
general do not pose a memory safety problem (those that do should do checks
like dynamic arrays do, but that's not the norm).

As for -boundschecks=off, that arguably shouldn't even exist. It can already
be gotten around using the ptr property if you really want that extra speed,
and the vast majority of programs shouldn't even consider using it, because
skipping the bounds checking in arrays is just begging for memory corruption
problems.

- Jonathan M Davis



More information about the Digitalmars-d-learn mailing list