Optionals and Weak References

In Argentum, associative reference (also known as weak) is one of fundamental built-in types. Such reference is easily created, copied, passed, and stored. It is not a pointer, it is rather a Schrodinger box that may or may not have a pointer inside:

class MyClass {
   i = 42;
   field = &MyClass;   // field; weak reference; "empty"
}

a = &MyClass;          // local variable; weak; "empty"
realObject = MyClass;  // temporary pointer to a freshly created instance of `MyClass`

a := &realObject;      // now `a` holds a pointer to the `realObject`

realObject.field := a; // now the object's field points to itself (which is ok for weaks)

The process of &-weak dereferencing includes:

  • checking that &-weak actually has pointer to something,
  • that its target still exists,
  • and that it resides in the same thread.

The result of these checks is a temporary reference to the object, wrapped in an optional (?T) , which not only signals the availability of the object through this reference but also prevents its deletion.

The above-described dereferencing has no explicit syntax. It is performed automatically wherever &T is transformed into ?T. For example, in the "?" or ":"-operators:

// If `a` points to an object, print its field `i`
a ? log("This object exists and has i={_.i}");

Here, the ?-operator expects to get ?T on the left, so the &weak variable a will be locked, and on success, it will be passed to the right operand as "_" variable of type MyClass where _.i extracts its field.

As a result:

  • In Argentum, it is impossible to access lost weak references.
  • This check has lightweight syntax.
  • It generates a temporary value ("_" or a name defined by the programmer through ?`name), and this temporary name has a lifetime limited by the right operand of the ? operator.

Leave a Reply

Your email address will not be published. Required fields are marked *