Bad array indexing is considered deadly
Steven Schveighoffer via Digitalmars-d
digitalmars-d at puremagic.com
Wed May 31 07:11:05 PDT 2017
On 5/31/17 10:07 AM, Steven Schveighoffer wrote:
> Here is complete implementation (should be @safe too):
>
> struct ExArr(T, size_t dim)
> {
> T[dim] _value;
> alias _value this;
> ref inout(T) opIndex(size_t idx, string fname = __FILE__, size_t
> linenum = __LINE__) inout
> {
> if(idx >= dim)
> throw new Exception("Index out of bounds", fname, linenum);
> static ref x(ref inout(T[dim]) val, size_t i) @trusted { return
> val.ptr[i]; }
> return x(_value, idx);
> }
> }
Just realized, that @trusted escape is just so unnecessarily verbose.
struct ExArr(T, size_t dim)
{
T[dim] _value;
alias _value this;
ref inout(T) opIndex(size_t idx, string fname = __FILE__, size_t
linenum = __LINE__) inout @trusted
{
if(idx >= dim)
throw new Exception("Index out of bounds", fname, linenum);
return _value.ptr[idx];
}
}
-Steve
More information about the Digitalmars-d
mailing list