我正在使用 Spring4D 在 Delphi 10.3 Rio 中测试智能指针。这是我的测试程序。我创建了一个泛型TObjectList
,我想使用简单TObject
的 s 添加到这个列表中Shared.Make(TTestObj.Create)
。问题是每当我向列表中添加一个对象时,前一个对象就会被释放。查看我的程序的输出。有谁知道如何解决这个问题?
program TestSmartPointer;
{$APPTYPE CONSOLE}
uses
Spring,
Diagnostics,
Classes,
SysUtils,
System.Generics.Collections;
type
TTestObj = class
private
FDescription: string;
public
property Description: string read FDescription write FDescription;
destructor Destroy; override;
end;
TTestList = class(TObjectList<TTestObj>)
destructor Destroy; override;
end;
var
LISTITEMCOUNT: integer;
LISTCOUNT: integer;
procedure Test_SmartPointer;
begin
Writeln('SmartPointer test started');
var lTestList := Shared.Make(TTestList.Create)();
lTestList.OwnsObjects := false;
for var i := 1 to 10 do
begin
var lTestObj := Shared.Make(TTestObj.Create)();
// var lTestObj := TTestObj.Create;
lTestObj.Description := i.ToString;
Writeln('TestObj added to Testlist with description ' + lTestObj.Description);
lTestList.Add(lTestObj);
end;
Writeln('SmartPointer test finished');
end;
{ TTestObj }
destructor TTestObj.Destroy;
begin
Writeln(format('TTestObj with description %s is destroyed', [FDescription]));
inherited;
end;
{ TTestList }
destructor TTestList.Destroy;
begin
Writeln('TTestList is destroyed');
inherited;
end;
begin
Test_SmartPointer;
Readln;
end.