Auto-updated self-references

I’ve been scanning a bit through these two posts about the self-referential structs problem and the rental and owning_ref crates working around it.

I just a naive question here: how hard would it be to design smart pointers, dedicated to self-reference, that would automatically update themselves when the self-referential struct containing them is moved around? The idea is to trade a little bit of runtime performance to keep safe self-referential structs.

When I write “how hard would it be”, I don’t mean “I think it wouldn’t be too hard”, I really mean “I have no idea what this would imply in terms of low-level implementation of the move operation”. Any thoughts on this?

You could use my rel-ptr crate to help make self-referential types that move. Other than that you can use the Pin<_> api, but that is hard to get right.

1 Like

A move is a simple memory copy, by design lacking any hooks for user code to intervene.


Ah, I get it. The problem lies in that there is no hook into the move operation, right? Building such a hook would imply… what? Would it imply that every memcopy operation be pre-checked for the triggering of a hook? I guess this would be dramatic for runtime performance X)

Would it be possible then, at intermediate level, to leave the memcopy instructions as-is but append an updateselfpointers procedure after each occurence of it? This would imply no hook into memcopy and the responsibility for guaranteeing safety would be the compiler responsibility?
Or maybe this makes no sense at all?

No, because that is still a move hook. Having any move hook would break almost all unsafe code, because pretty much all unsafe code assumes that a move is just a memcpy.

What are you trying to build, because you might be able to build it without making a self referential type.

1 Like

unsafe code today does things like:

  • Call realloc to resize a Vec.
  • Perform memcpys of a T through an erased type like *mut u8
  • Call external C functions that may perform copies of data.

The compiler could not detect all of this.


Hehe, I’m not actually trying to build anything. I was just curious why this though I had about the self-reference problem wasn’t discussed anywhere I looked. Now I think I understand why this approach is almost impossible. Thank you guys for discussion :slight_smile:

1 Like