C++ pattern matching is coming

Dukc ajieskola at gmail.com
Mon Oct 24 20:25:38 UTC 2022


On Monday, 24 October 2022 at 01:01:03 UTC, Steven Schveighoffer 
wrote:
> Is this a bug? Because I can't do this from @trusted code:
>
> ```d
> void foo() @trusted
> {
>     static struct T
>     {
>         Exception ex;
>         ubyte[] buf;
>     }
>
>     scope buffer = new ubyte[100];
>     T t;
>
>     t.ex = new Exception("hello");
>     t.buf = buffer;
>     throw t.ex;
> }
>
> void main() @safe
> {
>     foo();
> }
> ```

Hmm, this looks like it probably should work because of having 
the `@trusted` attribute. In a `@safe` function it'd be right to 
fail because `T t` is inferred as `scope` due to the statement 
`t.buf = buffer;`.

However, using `@trusted` just to accomplish this is asking for 
trouble. Instead, you should make the function checkably safe:
```D
void foo() @safe
{
     static struct T
     {
         Exception ex;
         ubyte[] buf;
     }

     scope buffer = new ubyte[100];
     T t;

     auto helloEx = new Exception("hello");
     t.ex = helloEx;
     t.buf = buffer;
     throw helloEx;
}
```

Well, in this example anyway. I understand this is just a 
simplified example, and `@trusted` may be necessary with your 
real problem.




More information about the Digitalmars-d mailing list