Member delegate/fp to another member in same object?

Adam D. Ruppe via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Tue May 2 10:32:10 PDT 2017


On Tuesday, 2 May 2017 at 17:08:11 UTC, Juanjo Alvarez wrote:
> struct S {
>   int someState;
>   void some_foo() { return this. someState;}
>
>   void delegate() foo;
>
>   void enable() {
>     foo = &some_foo;
>   }
> }

That's actually illegal in D. It will compile, but has undefined 
behavior because the compiler is free to move the struct around 
without giving you a chance to update the delegate. You are 
liable for random crashes doing that.

You'd be better off using a function pointer instead of a 
delegate and making the user pass `this` to it explicitly, or 
making it a class rather than a struct, which the compiler will 
not move. (or a struct only ever used by pointer, a diy class 
basically)


More information about the Digitalmars-d-learn mailing list