Force an object to only have a single non-weak reference?

I ran across a situation where I really wished I could force an object to only have a single strong owner and all other references to it would have to be weak/temporary. (Is this what move-only types would be for?) For example, I have a game object that has a destroy() function on it. Once called the object is meant to be permanently destroyed so I'd really like if all other references to that object could just go away without having to litter my code with something that checks for isDestroyed all the time. If I could force the object to always be retained weak everywhere except in the game manager itself, then this problem would be visible to the type system and force me to properly deal with it everywhere without ever accidentally missing any.

Yeah, this is the sort of thing move-only types would be able to statically enforce. Without move-only types, you might be able to dynamically enforce this property, by having your deinit set a sentinel value somewhere and asserting that the deinit was in fact called at points where you expect the lifetime of your strong owner to have ended.

3 Likes

Thanks Joe - that's a good idea! I'll sprinkle a few asserts around. I didn't understand the point of move-only types initially, but when I started really thinking about this project's design, it all suddenly made a lot more sense.