Array Indexing/Slicing Range Checking, Exceptions and @nogc

Adam D. Ruppe via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Wed Mar 30 06:38:40 PDT 2016


On Wednesday, 30 March 2016 at 13:12:49 UTC, Nordlöw wrote:
> I'm however uncertain about how to implement error handling of 
> bounds checking and how these interact with `@nogc`. My main 
> goal is to match semantics of builtin D arrays and slices.

I would actually cheat on this somehow.... and actually, there's 
a better way entirely:

Don't use your ptr method. Instead, make it a slice method: 
`return _store[0 .. _length];`

Now you can just index it internally and let the compiler 
automatically insert range checks. When you need the pointer, you 
still have slice.ptr.

So punt the problem to the compiler. This will also ensure you 
always use it correctly too.


If you don't want to do that, you could cheat on the range error 
a couple other ways too:

1) define a function to allocate the exception that lies about 
being nogc. It is an Error and unrecoverable anyway - you are 
allowed to throw them from nothrow too!

2) Define a fake slice and index into it, knowing it is out of 
bounds so the compiler generates the error. Dangerous in -release 
mode though!

3) Pre-allocate a RangeError object. Meh, I wouldn't do that, but 
listing it because you could.


More information about the Digitalmars-d-learn mailing list