Delphi manages free memory

SITUATION

I am learning Delphi from a book by Marco Cantu, and I already have experience with OOP, because I usually work with Java and PHP. To better understand what I'm reading, I did this test:

type
 TFraction = class
  private
   number: double;
   num, den: integer;
   fraction: string;
   function hcf(x: integer; y: integer): integer;
  public
   constructor Create(numerator: integer; denominator: integer); overload;
   constructor Create(value: string); overload;
   function getFraction: string;
 end;

This is a super simple class that converts a decimal number to a fraction. I do not include other parts of the code where I define constructors and functions, as they are not useful for my question. I create an object this way.

var a: TFraction;
begin

 a := TFraction.Create(225, 35);
 ShowMessage(a.getFraction);
 //The output of ^ is 45/7
 a.Free;

end;

Question

From what I learned, I know that I need to get rid of the object as soon as I used it, and actually I use Free. This way I free up memory and avoid memory leaks.

, , destructor. Free Destroy. Free, , . , , ?

, Free? Destroy?

+4
2

, , - , . , . , () , .

, , Destroy - , . Free , - . Free , nil , Destroy, nil.

, :

type
  TMyObject = class(TObject)
  private
    FSomeOtherObject: TSomeOtherObject;
  public
    constructor Create;
    destructor Destroy; override;
  end;

constructor TMyObject.Create;
begin
  inherited;
  FSomeOtherObject:= TSomeOtherObject.Create;
end;

destructor TMyObject.Destroy;
begin
  FSomeOtherObject.Free;
  inherited;
end;

, , , - . , Create Free - ? , . try / finally...

a := TFraction.Create(225, 35);
try 
  ShowMessage(a.getFraction);
finally
  a.Free;
end;

, , try finally, finally end.

+7

, , destructor. Free Destroy.

Free() , .

Destroy() .

Free, , . , , ?

. , . - , .

, Free? Destroy?

Destroy(), Free() Destroy() .

+3

Source: https://habr.com/ru/post/1651620/


All Articles