Đoạn mã sau cố gắng sử dụng tính năng đếm tham chiếu của Delphi.Rò rỉ bộ nhớ khi sử dụng tính năng đếm tham chiếu của Delphi
Tuy nhiên, FastMM4 trong báo cáo FullDebugMode DoStuff1
cho rò rỉ bộ nhớ trong khi DoStuff2
thì không. Bạn có thể giúp bình luận về lý do tại sao? Hai thủ tục này có nên hoạt động giống hệt nhau không?
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.
Không sử dụng dàn diễn viên như vậy. Sử dụng 'I: = OperationClass.Create as ITestFunc;'. Bạn có thể thực sự chỉ làm 'I: = OperationClass.Create;', nhưng điều đó không đặt số tham chiếu là 1, điều này có thể gây ra vấn đề. –
@Rudy Nó đặt số ref là 1 khi tôi được chỉ định. –
@Xichen Lớp học của bạn sẽ cần một nhà xây dựng ảo –