Struct WeakRef
Extremely simple intrusive weak reference implementation.
struct WeakRef(T)
if (isReferenceType!T && hasDestructionFlag!T);
WeakRef serves one task: to notice a dangling pointer after object destruction. For example, class A owns object B, and class C needs to temporarily save B. So C accepts WeakRef of B. If object A decides to destroy B, C will stay with null reference.
Object B must satisfy some requirements, because of intrusive nature of WeakRef. See example below.
Constructors
Name | Description |
---|---|
this
(object)
|
Create a weak reference. object must be valid, of course.
|
Fields
Type | Name | Description |
---|---|---|
T |
data
|
|
const(bool)* |
flag
|
Methods
Name | Description |
---|---|
get
()
|
Get the object reference |
nullify
()
|
Set this reference to point nowhere |
opCast
()
|
True if the object exists |
opEquals
(s)
|
Allows to use WeakRef with destroyed item as key in associative arrays |
toHash
()
|
Allows to use WeakRef with destroyed item as key in associative arrays |
Limitations
WeakRef cannot forward custom opEquals
and toHash
calls,
because their results need to be consistent before and after object destruction.
Example
class B
{
bool* destructionFlag;
this()
{
destructionFlag = new bool;
}
~this()
{
*destructionFlag = true;
}
}
WeakRef!B reference;
assert(!reference);
B b = new B;
reference = weakRef(b);
assert(b == reference .get);
assert(reference);
WeakRef!B ref2 = reference;
ref2 .nullify();
assert(!ref2);
destroy(b);
assert(!reference);