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:
class MyClass
{
public:
MyClass() { refCount = 1; weakRefFlag = 0; }
void Release()
{
if( refCount == 1 && weakRefFlag )
{
weakRefFlag->Set(true);
}
delete this;
}
{
if( !weakRefFlag )
{
if( !weakRefFlag )
}
return weakRefFlag;
}
static MyClass *Factory() { return new MyClass(); }
protected:
~MyClass()
{
if( weakRefFlag )
weakRefFlag->Release();
}
int refCount;
};
A lockable shared boolean.
Definition: angelscript.h:4306
AS_API void asAcquireExclusiveLock()
Acquire an exclusive lock.
AS_API int asAtomicDec(int &value)
Decrements the value by one and returns the result as a single atomic instruction.
AS_API void asReleaseExclusiveLock()
Release an exclusive lock.
AS_API int asAtomicInc(int &value)
Increments the value by one and returns the result as a single atomic instruction.
AS_API asILockableSharedBool * asCreateLockableSharedBool()
Create a lockable shared boolean.
The asBEHAVE_GET_WEAKREF_FLAG behaviour for this class is registered like this:
engine->RegisterObjectType(
"MyClass", 0,
asOBJ_REF);
@ asCALL_THISCALL
A thiscall class method.
Definition: angelscript.h:311
#define asMETHOD(c, m)
Returns an asSFuncPtr representing the class method specified by class and method name.
Definition: angelscript.h:773
@ asBEHAVE_ADDREF
AddRef.
Definition: angelscript.h:447
@ asBEHAVE_RELEASE
Release.
Definition: angelscript.h:449
@ asBEHAVE_GET_WEAKREF_FLAG
Obtain weak ref flag.
Definition: angelscript.h:451
@ asOBJ_REF
A reference type.
Definition: angelscript.h:329
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.