Assigning a static array
H. S. Teoh
hsteoh at quickfur.ath.cx
Thu Apr 18 16:15:06 PDT 2013
On Thu, Apr 18, 2013 at 02:43:54PM -0700, Ali Çehreli wrote:
> On 04/18/2013 02:06 PM, Brad Anderson wrote:
> >Is this supposed to be allowed:
> >
> >ubyte[] a;
> >ubyte[16] b;
> >a = b;
> >assert(a.ptr == b.ptr);
> >
> >Because if so that makes it terribly easy to do a bug like this (as I
> >just saw in IRC):
> >
> >struct A
> >{
> > ubyte[] a;
> > this(ubyte c)
> > {
> > ubyte[16] b;
> > b[] = c;
> > this.a = b; // a now points at an immediately invalid static
> >array
> > }
> >}
>
> There is a similar problem with the automatically generated array arguments.
>
> The following constructor takes any number of ints that come in array form:
>
> import std.stdio;
>
> struct S
> {
> int[] a;
>
> this(int[] args...)
> {
> a = args;
> }
>
> void foo()
> {
> writeln(a);
> }
> }
[...]
Yeah I got bitten by this before. Took me several days to find the
problem, 'cos it was nested deep inside a complex data structure, and at
a glance it doesn't *look* wrong.
I'm all for making this @system at the very least, if not outright
compile error. Storing a persistent reference to a stack-allocated
object is outright wrong... in the case of variadic array args, if the
compiler can't prove that args will *always* be a dynamic array, then
any attempt to save a reference to it should be rejected outright IMO.
T
--
It is impossible to make anything foolproof because fools are so ingenious. -- Sammy
More information about the Digitalmars-d-learn
mailing list