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);
    }
}

void main()
{
    S[] a;

    foreach (i; 0 .. 2) {
        a ~= S(i, i, i);  // <-- WARNING temporary array
    }

    foreach (e; a) {
        e.foo();
    }
}

The program prints the following because the temporary arrays that are generated when calling the constructors are long gone:

[1, 1, 1]
[1, 1, 1]

The programmer *may have* ;) expected the following output:

[1, 1, 1]
[2, 2, 2]

Ali

Reply via email to