I know an interfaced object is reference counted, so need not to manually free it. But if it has a TObject inherited member, should I manually free this member in the destructor?
Consider the following code:
program Project2;
{$APPTYPE CONSOLE}
{$R *.res}
uses
System.SysUtils,
System.Classes;
type
ITestInterface = interface(IInvokable)
['{A7BDD122-7DC6-4F23-93A2-B686571AB2C8}']
procedure TestMethod;
end;
TTestObj = class(TInterfacedObject, ITestInterface)
constructor Create;
destructor Destroy; override;
private
FData: TStrings;
public
procedure TestMethod;
end;
{ TTestObj }
constructor TTestObj.Create;
begin
FData := TStringList.Create;
end;
destructor TTestObj.Destroy;
begin
Writeln('Destroy'); // This line won't apear in the console ouput as the destructor won't be called.
FData.Free; // Who guarantees this member will be freed ?
inherited;
end;
procedure TTestObj.TestMethod;
begin
Writeln('TestMethod');
end;
{ Main }
procedure Main;
var
TestObj: TTestObj;
begin
TestObj := TTestObj.Create;
TestObj.TestMethod;
TestObj := nil; // TestObj should be freed at this moment ?
end;
begin
Writeln('Program start!');
Main;
Writeln('Program end.');
Readln;
end.
The program output:
Program start!
TestMethod
Program end.
It means the constructor was not been called, and the member FData
was not been freed ?
What should I do ? Thanks in advance.
TestObj: ITestInterface;
will make you happy. Or, well, at least will manage to do what you expect. – VictoriaTTestObject
does not inherit from two classes: it inherits fromTInterfacedObject
and implements the interface. There is only one destructor. I don't know what @Victoria means here, but it seems pretty irrelevant. – Rudy Velthuis