SharedObject¶
Usage
use SharedObject;
Shared
(along with Owned
) manage the
deallocation of a class instance. Shared
is meant to be used when
many different references will exist to the object and these references need
to keep the object alive.
To use Shared
, allocate a class instance following this
pattern:
var mySharedObject = new Shared(new MyClass(...));
When mySharedObject and any copies of it go out of scope, the class instance it refers to will be deleted.
Copy initializing or assigning from mySharedObject will make other variables refer to the same class instance. The class instance will be deleted after all of these references go out of scope.
var globalSharedObject:Shared(MyClass);
proc makeGlobalSharedObject() {
var mySharedObject = new Shared(new MyClass(...));
globalSharedObject = mySharedObject;
// now mySharedObject is deinitialized, but the MyClass
// instance is not deleted until globalSharedObject is deinitialized.
}
Shared
supports coercions to the class type as well as
coercions from a Shared(T)
to Shared(U)
where T
is a
subclass of U
. See Owned
for examples
of these coercions.
-
record
Shared
¶ The
Shared
manages the deletion of a class instance in a way that supports multiple owners of the class instance.This is currently implemented with task-safe reference counting.
-
proc
forwarding_expr2_p
()¶
-
proc
init
(p) Initialize a
Shared
with a class instance. ThisShared
will take over the deletion of the class instance. It is an error to directly delete the class instance while it is managed byShared
.Arguments: p -- the class instance to manage. Must be of class type.
-
proc
init
(src: Shared(?)) Copy-initializer. Creates a new
Shared
that refers to the same class instance as src. These will share responsibility for managing the instance.
-
proc
deinit
()¶ The deinitializer for
Shared
will destroy the class instance once there are no longer any copies of thisShared
that refer to it.
-
proc ref retain(newPtr: p.type )
Change the instance managed by this class to newPtr. If this record was the last
Shared
managing a non-nil instance, that instance will be deleted.
-
proc