Il codice seguente tenta di utilizzare la funzione di conteggio dei riferimenti di Delphi.Perdita di memoria quando si utilizza la funzione di conteggio dei riferimenti di Delphi
Tuttavia, FastMM4 nei rapporti FullDebugMode DoStuff1
fornisce perdite di memoria mentre non lo è DoStuff2
. Puoi aiutare a commentare sul perché? Non dovrebbero queste due procedure comportarsi esattamente allo stesso modo dietro la scena?
program Project_SO;
{$APPTYPE CONSOLE}
uses
FastMM4,
SysUtils;
type
ITestFunc = interface
['{B3F6D9A7-FC77-40CE-9BBF-C42D7037A596}']
function DoIt(X,Y: Integer): Integer;
end;
TTestFunc = class(TInterfacedObject, ITestFunc)
public
function DoIt(X,Y: Integer): Integer;
end;
TTestFuncClass = class of TTestFunc;
{ TTestFunc }
function TTestFunc.DoIt(X, Y: Integer): Integer;
begin
Result := X + Y;
end;
function DoStuff1(Num1, Num2: Integer; OperationClass: TTestFuncClass): Integer;
begin
Result := ITestFunc(OperationClass.Create).DoIt(Num1, Num2);
end;
function DoStuff2(Num1, Num2: Integer; OperationClass: TTestFuncClass): Integer;
var I: ITestFunc;
begin
I := ITestFunc(OperationClass.Create);
Result := I.DoIt(Num1, Num2);
end;
begin
Writeln(IntToStr(DoStuff1(3, 6, TTestFunc)));
Writeln(IntToStr(DoStuff2(3, 6, TTestFunc)));
end.
Non usare un cast del genere. Usa 'I: = OperationClass.Create come ITestFunc;'. In realtà potresti semplicemente fare "I: = OperationClass.Create;", ma questo non imposta il conteggio dei riferimenti su 1, il che può causare problemi. –
@Rudy Imposta il conteggio rif. A 1 quando sono assegnato a. –
@Xichen La tua classe avrà bisogno di un costruttore virtuale –