IMPORTANT: To view this page as Markdown, append `.md` to the URL (e.g. /docs/manual/basics.md). For the complete Mojo documentation index, see llms.txt.
Skip to main content
Version: Nightly
For the complete Mojo documentation index, see llms.txt. Markdown versions of all pages are available by appending .md to any URL (e.g. /docs/manual/basics.md).

WeakPointer

struct WeakPointer[T: Movable & ImplicitlyDestructible]

Non-owning atomic reference to an ArcPointer's allocation.

A WeakPointer may not be directly subscripted to dereference to the value it conceptually points to.

Instead, a WeakPointer may be .try_upgrade()ed into an ArcPointer[T] if there is at least one ArcPointer[T] for the value still live.

This may be used for self-referential structures, such as doubly linked lists or trees with parent refs, to avoid creating ownership cycles that would leak if dropped.

If all ArcPointer[T] to a value are dropped but WeakPointer[T] remain, the value will be destroyed. After this point, .try_upgrade()ing a WeakPointer[T] to that value will always return None.

Parameters

Implemented traits

AnyType, Copyable, ImplicitlyCopyable, ImplicitlyDestructible, Movable, RegisterPassable

Methods

__init__

__init__() -> Self

Create a null WeakPointer, with no inner. This can be used for transient construction states for self-referential structures.

__init__(*, downgrade: ArcPointer[T]) -> Self

Creates a new Weak pointer from an associated ArcPointer.

Args:

  • downgrade (ArcPointer[T]): The value that this creates a WeakPointer referring to.

Returns:

Self: A new Weak pointer sharing this allocation.

__init__(*, copy: Self) -> Self

Increment the weak count and share the allocation.

Args:

  • copy (Self): The existing WeakPointer to share an allocation with.

__del__

__del__(deinit self)

Decrement the weak count and free the allocation if last.

try_upgrade

try_upgrade(self) -> Optional[ArcPointer[T]]

Attempts to obtain a strong reference.

Returns:

Optional[ArcPointer[T]]: An ArcPointer sharing the allocation, or None if the payload has already been destroyed (strong count reached 0).

strong_count

strong_count(self) -> UInt64

Returns the current strong count, or 0 if the payload is gone.

Returns:

UInt64: The current number of strong references to the allocation.

weak_count

weak_count(self) -> UInt64

Returns an approximate count of WeakPointers to this shared value.

This can be off by one in the presence of concurrent activity.

Returns:

UInt64: The approximate number of outstanding WeakPointers.