Mojo struct
ArcPointer
@register_passable
struct ArcPointer[T: Movable]
Atomic reference-counted pointer.
This smart pointer owns an instance of T
indirectly managed on the heap.
This pointer is copyable, including across threads, maintaining a reference
count to the underlying data.
When you initialize an ArcPointer
with a value, it allocates memory and
moves the value into the allocated memory. Copying an instance of an
ArcPointer
increments the reference count. Destroying an instance
decrements the reference count. When the reference count reaches zero,
ArcPointer
destroys the value and frees its memory.
This pointer itself is thread-safe using atomic accesses to reference count the underlying data, but references returned to the underlying data are not thread-safe.
Subscripting an ArcPointer
(ptr[]
) returns a mutable reference to the
stored value. This is the only safe way to access the stored value. Other
methods, such as using the unsafe_ptr()
method to retrieve an unsafe
pointer to the stored value, or accessing the private fields of an
ArcPointer
, are unsafe and may result in memory errors.
For a comparison with other pointer types, see Intro to pointers in the Mojo Manual.
Examples:
from memory import ArcPointer
var p = ArcPointer(4)
var p2 = p
p2[]=3
print(3 == p[])
from memory import ArcPointer
var p = ArcPointer(4)
var p2 = p
p2[]=3
print(3 == p[])
Parameters
- T (
Movable
): The type of the stored value.
Implemented traits
AnyType
,
CollectionElement
,
CollectionElementNew
,
Copyable
,
ExplicitlyCopyable
,
Identifiable
,
Movable
,
UnknownDestructibility
Methods
__init__
__init__(out self, owned value: T)
Construct a new thread-safe, reference-counted smart pointer, and move the value into heap memory managed by the new pointer.
Args: