1

私はインターフェイスを使用していません (そのため、オブジェクトには参照カウントがありません)。オブジェクトは他の多くのオブジェクトから参照される可能性があり、ダングリング ポインターを処理する必要があります。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; 
4

1 に答える 1