On Wednesday, 17 February 2021 at 19:42:00 UTC, tsbockman wrote:
On Wednesday, 17 February 2021 at 17:45:01 UTC, H. S. Teoh wrote:
I.e., the following is NOT a good idea:

        struct S {
                void delegate() member;
                this() {
                        member = &this.impl;
                }
                private void impl();
        }

because a pointer to S is stored inside S itself, so as soon as S gets copied or moved, the delegate context pointer is no longer valid (or else points to a different copy of the struct than the one it will be called from).

A copy constructor and opAssign can be used to update pointers that are relative to &this:
    https://dlang.org/spec/struct.html#struct-copy-constructor

Unfortunately this is not enough, because the compiler is free to implicitly move struct instances in memory any time it wants to. See the bug report below for more details:

https://issues.dlang.org/show_bug.cgi?id=17448

Until D gets move constructors, structs with interior pointers should be avoided.

Reply via email to