WeakPointer¶
The weakPointer
type is a special smart pointer type designed to be used in
tandem with shared
objects.
A weakPointer
provides a reference to a shared
class object without
requiring it to stay allocated. Such a pattern is useful for implementing graph
or tree structures with bidirectional references, or for implementing cache-like
data structures that maintain a list of objects but don’t require them to stay
allocated.
A “strong” shared reference to the relevant class object can be obtained via
the upgrade
method, or by casting the
weakPointer to a shared t
or a shared t?
. If the underlying object is
not valid (i.e., its shared reference count has already dropped to zero
causing it to be de-initialized) the upgrade attempt will fail.
Weak pointers are implemented using task-safe reference counting.
Warning
The weakPointer
type is experimental, please use this feature with caution.
- record weakPointer¶
- type classType¶
The shared class type referenced by this pointer
- proc init(c: shared)¶
Create a new weak pointer to a shared class instance ‘c’
Warning
The ‘weakPointer’ type is experimental and is likely to change in the future
- proc init=(const ref src: weakPointer)¶
Copy-initialize a new
weakPointer
from an existingweakPointer
.Increments the weak-reference count.
- proc upgrade(): this.classType?¶
Attempt to recover a shared object from this weakPointer
If the pointer is valid (i.e., at least one shared reference to the data exists), a nilable shared object will be returned.
If the pointer is invalid (or the object itself is nil) then a nil value will be returned.
- proc deinit()¶
When a
weakPointer
is deinitialized, the weak reference count is decremented.If there are no other references (weak or strong), the backing pointer is freed.
- proc getWeakCount(): int¶
Get the number of
weakPointers
currently pointing at the sameshared
class as this one.
- proc getStrongCount(): int¶
Get the number of
shared
variables currently pointing at the sameshared
class as thisweakPointer
- operator :(const ref x: weakPointer, type t: shared class?)
Cast a weak pointer to a nilable class type.
If the referenced class has already been deinitialized, or is itself
nil
, this cast will return anil
value.Otherwise it will return a nilable
shared
t
.
- operator :(const ref x: weakPointer, type t: shared class) throws
Cast a weak pointer to a non-nilable class type.
If the referenced class has already been deinitialized, or is itself
nil
, this cast will throw aNilClassError
.Otherwise it will return a
shared
t
.
- operator =(ref lhs: weakPointer, rhs: weakPointer)¶
Assign one existing
weakPointer
to an other.Decrements the weak-reference count of the
lhs
pointer.This will result in the deinitialization of the
lhs
’s backing pointer if it is the lastweakPointer
orshared
that points to its object.
- proc weakPointer.writeThis(ch) throws¶