Immutability and arrays

Stanislav Blinov stanislav.blinov at gmail.com
Tue Dec 14 15:53:21 UTC 2021


On Tuesday, 14 December 2021 at 15:28:30 UTC, Steven 
Schveighoffer wrote:

> All the other problems you are having are deriving from this 
> problem.

Not exactly. One of the problems seems to be a genuine bug:

```d
struct S
{
     int[] x;

     // doesn't even participate here, neither would postblit
     this(ref return scope inout S other)
     {
         x = other.x.dup;
     }

     void opAssign(ref return scope inout S other)
     {
         x = other.x.dup;
     }
}

void main()
{
     immutable(S)[] src = [S([1, 2]), S([3, 4])];

     auto dst = new S[src.length];

     //dst[0 .. $] = src[0 .. $]; // this fails to compile even 
with opAssign defined

     // this works:
     foreach (i, ref it; dst)
         it = src[i];
}
```

Spec: https://dlang.org/spec/arrays.html#array-copying

> ...contents of the array are the target of the assignment...

Per that wording, slice assignment should perform the equivalent 
of that foreach loop (after overlap checks, etc.). It doesn't, 
just tries implicit conversion, and fails.

Now, since we have copy ctors, slice assignment should, 
ostensibly, attempt to copy-assign elements (i.e. absent 
opAssign, try the copy ctor first).


More information about the Digitalmars-d-learn mailing list