Ensdo
Ensdo

Reputation: 19

Instantiating an object in Delphi without using a variable

TObject.Create().method;

Method(TObject.Create);

Does this type of memory call allocate on the heap or the stack? Does it need to be released?

Upvotes: 1

Views: 173

Answers (1)

Remy Lebeau
Remy Lebeau

Reputation: 595711

Delphi class instances are always allocated on the heap, and yes, they need to be released when you are done using them 1, via TObject.Destroy() (which TObject.Free() calls), eg:

obj := TObject.Create;
try
  obj.method;
finally
  obj.Free;
end;

obj := TObject.Create;
try
  Method(obj);
finally
  obj.Free;
end;

procedure Method(obj: TObject);
begin
  ...
  obj.Free;
end;

Method(TObject.Create);

function Method(obj: TObject): TObject;
begin
  ...
  Result := obj;
end;

Method(TObject.Create).Free;

And so on. Any object you Create with a constructor must be Destroy'ed with a destructor.

1: if you are running your code on a platform that uses ARC for object lifetime management (currently iOS, Android, and Linux), objects are reference counted and released automatically for you.

Upvotes: 5

Related Questions