Which is the best way to manage the life cycle of an object-to-object type?

TMyClass = class(TObject)
private
  FMyObject: TObject;
  function GetMyObject: TObject;
public
  property MyObject: TObject read GetMyObject write FMyObject;
end;

function TMyClass.GetMyObject: TObject;
begin
  if FMyObject = nil then
    FMyObject := TObject.Create;

  Result := FMyObject;
end;

Sometimes "MyObject" is not created internally, but is externally created and assigned to a parameter. If this object is created externally, I cannot release it in this context.

Should I create TList and Add in all objects that were created internally and destroy everything on the destructor?

How can I control the lifetime of a parameter if it is created internally or not? What do you propose to do? Is there any template for this?

+5
source share
3 answers

I set the flag in Property Setter

procedure TMyClass.SetMyObject(AObject: TObject);
begin
  if Assigned(MyObject) and FIsMyObject then
    FMyObject.Free;
  FIsMyObject := False;
  FMyObject := AObject;
end;

function TMyClass.GetMyObject: TObject;
begin
  if FMyObject = nil then
  begin
    FMyObject := TObject.Create;
    FIsMyObject := True;
  end;

  Result := FMyObject;
end;

Destructor TMyClass.Destroy;
begin
    if FIsMyObject then
        FMyObject.Free;
end;
+7
source

, , - .

, ( ) . .

, , -

procedure TMyClass.SetMyObject(const Value: TObject);
begin
   MyObject.Assign(Value);
end;

, , Free . , , ...

+3

( , ) , , TObject, . , .

(: .)

  • , :

        property MyObject: TSomeAncestor read GetMyObject write SetMyObject;
      end;
    
    implementation
    
    type
      TMyObject = class(TSomeAncestor) ... end;
    
    destructor TMyClass.Destroy;
    begin
      if FMyObject is TMyObject then
        FMyObject.Free;
    
  • :

        property MyObject: TOwnedObject read GetMyObject write SetMyObject;
      end;
    
    implementation
    
    destructor TMyClass.Destroy;
    begin
      if FMyObject.Owner = Self then
        FMyObject.Free;
    

    , : Owner . .

  • TComponent, .

+1
source

All Articles