The next iteration of scope

via Digitalmars-d digitalmars-d at
Mon Mar 16 06:55:42 PDT 2015

On Monday, 16 March 2015 at 04:00:51 UTC, Zach the Mystic wrote:
> "Functions and methods can be overloaded on scope. This allows 
> efficient passing of RC wrappers for instance..."
> How does the compiler figure out which of the variables it's 
> passing to the parameters are `scope` or not? Does the caller 
> try the scoped overloads first by default, and only if there's 
> an error tries the non-scoped overloads? If so, what causes the 
> error?

Hmm... I guess it only makes sense for postblits and destructors. 
I'm not sure about constructors and opAssign, so I'll leave these 
out for now. I've changed the wiki page accordingly.

> "To specify that the value is returned through another 
> parameter, the return!ident syntax can be used...
> struct RC(T) if(is(T == class)) {
>     scope T payload;
>     T borrow() return {    // `return` applies to `this`
>         return payload;
>     }
> }"
> The example contains no use of `return!ident`.

I added an example.

> Also, what exactly does the `scope` on T payload get you? Is it 
> just a more specific version of `return` on the this parameter, 
> i.e. `return this.payload`? Why would you need that 
> specificity? What is the dangerous operation it is intended to 
> prevent?

Nick already answered that. I'll expand on his explanation:

Let's take the RC struct as an example. Instances of RC can 
appear with and without scope. Because structs members inherit 
the scope-ness from the struct, `payload` could therefore be an 
unscoped pointer. It could therefore be escaped unintentionally. 
By adding `scope` to its declaration, we force it to be scoped to 
the structs lifetime, no matter how it's accessed.

More information about the Digitalmars-d mailing list