Making sense out of scope and function calls

Dukc ajieskola at gmail.com
Mon Nov 14 08:42:16 UTC 2022


On Sunday, 13 November 2022 at 19:06:40 UTC, 0xEAB wrote:
> Why does only the latter sample compile?
> The former leads to the following warning:

Are you using the `-preview=dip1000` compiler flag?

I didn't manage to reproduce this in a simple example of my own. 
The closest I equivalent I accomplished is this:
```
enum LowerCaseToken { u, l, c }

struct Foo {
     @safe:
     int* dummy;
     string[int][LowerCaseToken] _headers;

     this(return ref int i)
     {
         dummy = &i;
     }

     string[] getHeader(LowerCaseToken name) scope return
     {
         return _headers[name].values;
     }

     string[] getHeader(string name)() scope return
     {
         enum token = LowerCaseToken.l;
         // Error. Remove to compile
         auto x = &this;
         return this.getHeader(token);
     }
}

@safe void main()
{
     int x;
     auto foo = Foo(x);
     foo.getHeader!"h1"();
}
```

With `-preview=dip1000` this fails, but with a slightly different 
message to yours, "cannot take address of `scope` parameter 
`this` in `@safe` function `getHeader`". It's right to fail, 
because you cannot have any pointer (or array, or class) to point 
to a `scope` variable. D does not have any storage class for `x` 
that would protect the int pointed to by `dummy`, because 
`scope(Foo*)` means address of Foo is protected, not the address 
of whatever `dummy` and `_headers` point to.

However, this error only happens if I try to create a pointer to 
`this`, not when simply using `this`, plus the error is a bit 
different, so I'm not sure what's going on.


> (and why is the deprecation message printed twice?)

The function is a template. Perhaps it's instantiated twice. 
Another possibility, you have instantiated the mixin template 
that contains that function in your project twice.




More information about the Digitalmars-d-learn mailing list