我没有使用接口(所以对象没有引用计数)。这些对象可能被许多其他人引用,我需要处理悬空指针。FreeAndNil() 不能解决多个引用的问题。我需要当一个对象被销毁时,所有引用它的指针都会自动设置为 nil。或者,它可能类似于 C++ 中 std::weak_ptr 的 Expired() 方法。
我可以实现一个“弱智能指针”来做到这一点,但我不确定它是否是一个过于复杂的实现。你建议另一种解决方案吗?这是我正在考虑的未经测试的可能解决方案:
type
TWeakReferenceable = class
constructor Create();
destructor Destroy(); override; //Set ReferencedObject:=nil for all the weak references in FWeakReferenceList
private
FWeakReferenceList: TList; //List of weak references to this object
protected
procedure RegisterWeakReference(const AWeakReference: TWeakReference<TWeakReferenceable>); //Adds a weak reference
procedure UnregisterWeakReference(const AWeakReference: TWeakReference<TWeakReferenceable>); //Removes a weak reference
end;
type
TWeakReference<TObjectType: TWeakReferenceable> = class
constructor Create();
destructor Destroy(); override; //Destroys the object and calls UnregisterWeakReference(self) for the referenced object
private
FObjectReference: TObjectType;
procedure SetReference(AReferencedObject: TObjectType); //Calls UnregisterWeakReference(self) for the current reference, updates FObjectReference and calls RegisterWeakReference(self) for the referenced object
public
property ReferencedObject: TObjectType read FObjectReference write SetReference;
end;