Range non-emptyness assertions and opIndex

ag0aep6g via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Fri Jul 1 04:35:40 PDT 2016


On 07/01/2016 12:35 PM, Nordlöw wrote:
> What's the preferred way of reacting to emptyness in the members front,
> back, popFront, popBack --- using assert, enforce, throw, or simply
> relying on range-checking in the _store?

I think assert is the most common way of checking. Simply ignoring the 
possibility is also common, as it's considered a programming error to 
call front/popFront/etc on an empty range.

For the same reason, throwing an exception (via throw or via enforce) is 
less common. Exceptions are more for input/environment errors, not so 
much for programming errors.

> And what about using
>
>      debug assert()
>
> instead of
>
>      assert()
>
> typically when `_store`s `opIndex` already performs range-checking?
>
> I think this is a important issue since asserts are not optimized away
> in release mode and D is very much about performance.

Huh? Asserts are ignored with -release. The only exception is 
assert(false) which terminates the program immediately, even with -release.

A little example program:

----
void main()
{
     import std.stdio;
     int x = 1;
     assert(x != 1);
     writeln("hi");
}
----

When compiled without -release, the program throws an AssertError. With 
-release it prints "hi".


More information about the Digitalmars-d-learn mailing list