Getting the address of a member function at compile time inside a member function

Johan j at j.nl
Fri Jul 11 10:42:46 UTC 2025


On Monday, 7 July 2025 at 03:28:58 UTC, Steven Schveighoffer 
wrote:
> On Sunday, 6 July 2025 at 03:47:07 UTC, Walter Bright wrote:
>> When taking the address of a member function, a delegate is 
>> created, not a function pointer. The delegate is comprised of 
>> two members: a function pointer, and a context pointer (i.e. 
>> `this`). When the static fn is initialized, there is no `this` 
>> available at compile time, so it (correctly) fails to compile.
>
> That is not what happens when outside a member function. I 
> should have been more descriptive.
>
> ```d
> void function() fn = &S.bar; // ok!
> struct S {
>    void bar() {}
> ```

Very surprising that this works, looks like a clear bug to me 
because it's apparently also allowed for `bar` to access member 
variables. It results in nullptr dereference upon using `this` 
inside `bar`.

Failure example:
```d
import std.stdio;

void function() fn = &S.bar;
struct S {
   int x;
   void bar() { writeln(x); }
}

void main() {
     fn();
}
```
https://d.godbolt.org/z/E5jWb9Wd3

-Johan



More information about the Digitalmars-d mailing list