Why isn't there a WeakPointer type alongside ArcPointer in Mojo?

Hello Mojo community :waving_hand:

I’ve been working with ArcPointer[T] for shared ownership and atomic reference counting. However, I noticed there’s no equivalent weak pointer type (e.g., WeakPointer) with .downgrade() / .upgrade() behavior to support non-owning references or break reference cycles.

According to the official docs, ArcPointer[T] supports:

  • Strong ownership through atomic reference counting.
  • Shared access and thread safety in copying.
  • No mention of weak pointers or cycle-aware deallocation. docs.modular.com ArcPointer

I also didn’t find any standard library type like WeakPointer or methods such as .downgrade() or .upgrade().

My questions:

  1. Was leaving out WeakPointer an intentional design choice?
  2. Is there a recommended pattern in Mojo to handle cycles or create non-owning references safely?
  3. Are there plans to introduce weak references (or something similar) in a future release?

Thanks in advance for any clarification or guidance!

There was a PR to add a weak pointer type along with some fixes to ArcPointer, but the idea was to avoid burdening ArcPointer, which is typically used without a need for reference cycles (think Arc<Mutex<T>> in Rust) with the extra book keeping. Nobody has done the work for the separate, cycle-handling type mostly because nobody has had a need for a cyclic graph with an unbounded member set, so people will instead just allocate all the nodes at once, use references, and free them all at the same time.

Contributions are welcome, so if you want a copy of ArcPointer which does have a WeakPointer counterpart we should be able to include it in the standard library. Right now, most of the data structures in the standard library are there because someone needed them, since Mojo is running a fairly lean standard library unless there is a good motivating use-case. Cycle-handling atomic reference counting is one of those things that is probably a good idea. While you’re building it, you might also want to build in a switch to make it use atomic ops for extra speed in single-threaded contexts. We’ll circle back around when the concurrency model is more complete for stuff thread safety.

2 Likes

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.