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.
}
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 Shared(type t)

Default-initialize a Shared.

proc Shared(p, type t = p.type)

Initialize a Shared with a class instance. This Shared will take over the deletion of the class instance. It is an error to directly delete the class instance while it is managed by Shared.

Arguments:p -- the class instance to manage. Must be of class type.
proc Shared(src: Shared, type t = src.t)

Copy-initializer. Creates a new Shared that refers to the same class instance as src. These will share responsibility for managing the instance.

proc Shared.~Shared()

The deinitializer for Shared will destroy the class instance once there are no longer any copies of this Shared 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 ref clear()

Empty this Shared so that it stores nil. Deletes the managed object if this Shared is the last Shared managing that object. Does not return a value.

Equivalent to Shared.retain(nil).

proc borrow()

Return the object managed by this Shared without impacting its lifetime at all. It is an error to use the value returned by this function after the Shared goes out of scope.

proc =(ref lhs: Shared, rhs: Shared)

Assign one Shared to another. Deletes the object managed by lhs if there are no other Shared referring to it. On return, lhs will refer to the same object as rhs.