Strange copying of a constant array of structures

vit vit at vit.vit
Fri Jun 14 08:52:23 UTC 2024


On Friday, 14 June 2024 at 08:03:47 UTC, Vindex wrote:
> Last night I encountered some strange behavior of the dup 
> function.
>
> ```
> import std.stdio;
>
> struct S {
>     int x;
>     int y;
>     int[] arr;
>     this(ref return scope const S rhs) {
>         writeln("copy ctor");
>         this.x = rhs.x;
>         this.y = rhs.y;
>         this.arr = rhs.arr.dup;
>     }
> }
>
> void main() {
>     const S[] array = [S(0, 0), S(1, 2)];
>     S[] copy = array.dup;  // error
> }
> ```
>
> We have an issue:
> ```
> Error: none of the overloads of template `object.dup` are 
> callable using argument types `!()(const(S[]))`
> ```
>
> But(!) if we remove the dynamic array field from the structure, 
> everything works.
>

This is declaration of dup:
````
@property T[] dup(T)(const(T)[] a)
     if (is(const(T) : T))			
{
     import core.internal.array.duplication : _dup;
     return _dup!(const(T), T)(a);
}
````

constraint is(const(T) : T) ignore copy ctors. If S has property 
arr then const(S) is not implicitly convertable to mutable S.


More information about the Digitalmars-d mailing list