Inconsistent behavior shared struct vs non-shared storage - bug?

Iain Buclaw ibuclaw at gdcproject.org
Wed Jun 2 16:25:27 UTC 2021


On Wednesday, 2 June 2021 at 12:25:54 UTC, apz28 wrote:
>
>     struct S
>     {
>         C c;
>         this(C c)
>         {
>             counter++; writeln("this(): ", counter);
>             this.c = c is null ? new C() : c;
>         }

I suspect this is a topic better suited to d.learn, but you are 
missing a shared constructor.

```
shared this(shared C c)
{
     counter++; writeln("this(): ", counter);
     this.c = c is null ? new shared C() : c;
}
```

>     shared static this()
>     {
>         writeln("shared static this(1): ", counter);
>         static if (sharedit) s = cast(shared)S(null);
>         else s = S(null);
>         writeln("shared static this(2): ", counter);
>     }

The `sharedit` path constructs a non-shared object, which you 
cast to a shared one.  This causes a copy to occur, so what 
you're seeing is the destruction of the temporary.

Instead, construct a shared object.
```
static if (sharedit) s = shared(S)(null);
else s = S(null);
```


More information about the Digitalmars-d mailing list