Safe Regions with Deterministic Destruction

ag0aep6g anonymous at example.com
Tue Oct 27 18:24:47 UTC 2020


On Tuesday, 27 October 2020 at 16:56:40 UTC, Ola Fosheim Grøstad 
wrote:
> Yes, what I meant is that it is a value on the stack. But there 
> is a disconnect with classes. "oddball" passes as a class, even 
> though it would not pass as a struct:
>
> class A { int x; }
> class B { A a; }
>
> A oddball() {
>     scope B b = new B;
>     b.a = new A;
>     return b.a;
> }

`oddball` is neither a class nor a struct; it's a function.

If you change both `A` and `B` to structs and update the code to 
`A*` and `B*` where needed, then it works the same as with 
classes. If you change them to structs but don't use pointers, 
then it works differently because you're removing indirections.

> But WHY does this pass?
>
> class A { int x; }
> struct B { A a; }
>
> A misbehave() @safe {
>     scope A tmp = new A;
>     scope B b;
>     b.a = tmp;
>     return b.a;
> }

It doesn't? The last line gives "Error: scope variable `b` may 
not be returned". Remember to compile with `-preview=dip1000`.

[...]
> I understand. So for structs it works the same way as 
> scope-parameters?

I'm not sure if I understand the question, but as far as I 
understand `scope` locals and `scope` parameters work the same 
for all types. (Maybe there are subtle differences in life time. 
Maybe there are bugs. But basically they're the same thing.)


More information about the Digitalmars-d mailing list