1  package frost.core
 2  
 3  ====================================================================================================
 4  Holds a weak reference to an object. A weak reference allows access to an object, but does not
 5  participate in reference counting. Objects are destroyed when there are no remaining normal
 6  ("strong") references to them, even if one or more `Weak` references remain in memory.
 7  ====================================================================================================
 8  class Weak<T> {
 9      -- This is special cased within the compiler
10      @private
11      var value:T?
12  
13      @private
14      var _valid := true
15  
16      ================================================================================================
17      Creates a new `Weak`.
18      ================================================================================================
19      init(value:T?) {
20          self.value := value
21          if value !== null {
22              value.$flags ||= Frost.WEAK_REFERENCE_FLAG
23              Frost.addWeakReference(self)
24          }
25      }
26  
27      ================================================================================================
28      Returns the object referenced by this `Weak`. It is a safety violation to refer to an object
29      after it has been destroyed (by having no remaining strong references to it); this will be
30      detected using default compiler settings, but result in undefined behavior when safety checks
31      are disabled.
32      ================================================================================================
33      method get():T {
34          assert _valid, "dereferencing weak pointer after its referent was destroyed"
35          return value!
36      }
37  
38      @override
39      function get_toString():String {
40          return "Weak(\{value})"
41      }
42  }