Is @safe still a work-in-progress?
Walter Bright
newshound2 at digitalmars.com
Wed Aug 22 08:54:36 UTC 2018
On 8/21/2018 2:17 PM, Atila Neves wrote:
> Well, no. The syntax isn't the same for member functions. The examples from the
> actual DIP don't compile. There it says:
>
> -------
> scope can be applied to function return values (even though it is not a type
> qualifier). It must be applied to the left of the declaration, in the same way
> ref is:
>
> scope int* foo(); // applies to return value
> --------
>
> Except:
>
> -------
> struct MyStruct { scope int* foo() scope; }
>
> foo.d(1): Error: redundant attribute scope
> -------
> Meaning the first `scope` actually applies to `this`. Writing this out as a
> non-member function won't help me declare member functions!
>
> I still don't know how to return a ref/pointer that's scoped. And I thought I'd
> written code that did that. Maybe I did. I'm very confused.
Here's how you make it work:
---
@safe:
struct MyStruct {
ref int foo() return;
int* bar() return;
}
ref int sun() {
MyStruct s;
return s.foo(); // returning s.foo() escapes a reference to local variable s
}
int* moon() {
MyStruct s;
return s.bar(); // returning s.bar() escapes a reference to local variable s
}
---
In effect, the 'return' on 'foo()' says:
The return value of foo() contains the address of 'this', and if the return
escapes the scope of what 'this' is a ref to, then it's an error.
More information about the Digitalmars-d
mailing list