A devil self reference

Jonathan M Davis newsgroup.d at jmdavisprog.com
Wed Aug 15 21:42:11 UTC 2018


On Wednesday, August 15, 2018 10:40:49 AM MDT Alex via Digitalmars-d-learn 
wrote:
> Hi all.
> Finally, I arrived at something like this:
>
> ´´´
> void main()
> {
>   S!(sarr)[] sarr;
> }
>
> struct S(alias Reference)
> {
>   size_t id()
>   in
>   {
>       // not static assert, only because a pointer is never known in
> advance
>       assert(Reference.ptr <= &this);
>   }
>   do
>   {
>       return &this - Reference.ptr;
>   }
> }
> ´´´
>
> Of course, this does not compile, because I try to use an
> identifier before I defined it.
>
> However, the reason I dare to ask is, that all the stuff with the
> weird self reference is compile time known.
>
> So, is there a possibility to define something like the thing
> above?

What are you actually trying to do? Aside from the circular reference
issues, using the address of a struct like that is very risky, because if
the struct is ever moved, it will change. Also, even if the circular
reference worked, the struct is then in a dynamic array on the heap, whereas
the dynamic array itself is on the stack. So, you're trying to subtract a
stack pointer from a heap pointer.

- Jonathan M Davis






More information about the Digitalmars-d-learn mailing list