Even though AngelScript uses a garbage collector to resolve cyclic references weak references may still come in handy. Weak references are especifically useful in scenarios were an object wants to be able to access other objects, but do not want to kept them alive longer than necessary.
AngelScript supports weak references with the use of shared booleans. The code that wants to keep a weak reference to an object should obtain the weakref flag from that object, which is a shared boolean, and before using the pointer to the object it should check if this flag has been set to indicate that the object is no longer alive.
Script classes automatically supports weak references without the script writing having to do anything. Application registered types on the other hand must register the behaviour asBEHAVE_GET_WEAKREF_FLAG and implement the logic to set the flag upon destroying the object.
The following code shows how to do a thread safe implementation:
The asBEHAVE_GET_WEAKREF_FLAG behaviour for this class is registered like this:
The script language doesn't have a built-in syntax for weak references. Instead a standard weakref add-on has been implemented to provide this for the applications that wants to provide this support in the scripts.