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?
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.
const function parameters. The compiler isn't always smart enough to create a hidden variable to hold a reference (certainly not for object-based ARC, and only sometimes for interface-based ARC).procedure Method(const I: IMyInterface) and then do Method(MyObject.Create), this can cause problems, even if MyObject implements the interface. The refcount is 0. Only if you do Method(MyObject.Create as IMyInterface), things are safe.Free is too much. But if each time, you must decide whether to use Free or Destroy directly, each time you can make a mistake, and your choice can also become invalid if your code changes. So get in the habit of always using Free and never Destroy directly (except, of course, from another destructor) and you greatly reduce the risk of making mistakes. That is also the recommendation Borland and later producers of Delphi have always given out. ALWAYS USE FREE. In most situations, that is the only proper way to free anyway.