On Monday, 28 May 2018 at 13:51:49 UTC, James Blachly wrote:
Consider the below:

```
class C
{
    int x;
}

struct S
{
    int x;
}


void main()
{
        immutable C[] c = [ new C(), new C()];
        immutable S[] s = [ S(), S() ];
    immutable int[] i = [ 1, 2 ];

    auto x = c.dup;
    auto y = s.dup;
    auto z = i.dup;

}
```

This fails to compile with a `.dup` template matching error at line `auto x = c.dup;`. However, calling `.idup` works just fine. The immutable struct array and int array of course `.dup` just fine.

I would have guessed that changing the definition of `C[]` to `immutable(C)[]` would have also helped, but it did not.

Why are the class objects special in this case, and why does `immutable(C)[]` not help? I believed that this defined a dynamic array `c` which was itself mutable, the elements of which were immutable.

Thanks for insights.

I'm going to make a wild guess that .dup is a shallow copy and if the class has any members that are reference types only references to them are copied.

Which means that by creating a mutable duplicate of the class you essentially have a mutable reference to said member.

Even though in your example that isn't the case, then that's the only reason I can think of the restriction making sense.


Reply via email to