1
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?

0

1 Answer 1

5

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.

Sign up to request clarification or add additional context in comments.

8 Comments

Even with ARC I guess there could be leaks if nothing actually takes a reference. For instance if the function being called is a const parameter.
@DavidHeffernan yes, and that is a recurring mistake that people do make with ARC - directly instantiating objects in 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).
If Method takes an interface parameter which the object implements, it is automatically freed. Method(bla: ISomeInterface)
@dummzeuch: yes, but if you have a method with a const interface parameter, i.e. 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.
@Günther: Perhaps, sometimes, using 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.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.