说我有以下记录:
type
TTest = record
test1 : TTest1;
test2 : TTest2;
test3 : TTest3;
end;
pTTest = ^TTest;
TDictestDictionary = TDictionary<integer,pTTest>;
testDictionary : TDictestDictionary
写
是否足够 testDictionary := TDictionary<integer,pTTest>.Create;
然后添加如下项目:
testDictionary.AddOrSetValue(1,pValue);
还是需要初始化pValue?
但接下来会发生什么:
GetMem(pValue, Value);
testDictionary.AddOrSetValue(1,pValue);
FreeMem(pValue);
这些项会删除pValue指向的数据吗?
请帮助
另外,根据同样的想法,我可以这样:
Type
myClass = class(TObject)
private
FTest : TDictestDictionary ;
public
property propFTest : TDictestDictionary read getFTest() write setFTest()
但是我如何写getFTest()setFTest()
帮助。 谢谢
答案 0 :(得分:2)
如果你真的想在容器中存储指针,那么你需要在某个时刻分配内存。如果在容器仍包含对该内存的引用时释放内存,则容器的引用是无用的。它被称为陈旧指针。总是,持有陈旧的指针意味着你的代码有缺陷。
在我看来,没有必要在这里使用指针。您可以像这样声明字典:
TDictionary<Integer, TTest>
该容器包含您的记录副本,因此会自动管理生命周期。
答案 1 :(得分:0)
我同意大卫的观点。我觉得这里不需要指针。使用类和TObjectDictionary
然后您可以创建任意数量的视图,内存管理仍然很容易:一个TObjectDictionary
拥有其他TObjectDictionary
或TList<>
的类只是查看预先显示您的数据的不同。
这是灵感的单元。
unit TestDictionaryU;
interface
uses
System.Generics.Collections;
type
TTest1 = class
end;
TTest2 = class
end;
TTest3 = class
end;
TTest = class
test1: TTest1;
test2: TTest2;
test3: TTest3;
constructor Create;
destructor Destroy; override;
end;
TTestDictonary = class(TObjectDictionary<Integer, TTest>)
public
constructor Create;
function AddTest : TTest;
end;
implementation
{ TTest }
constructor TTest.Create;
begin
inherited;
test1 := TTest1.Create;
test2 := TTest2.Create;
test3 := TTest3.Create
end;
destructor TTest.Destroy;
begin
test1.Free;
test2.Free;
test3.Free;
inherited;
end;
{ TTestDictonary }
function TTestDictonary.AddTest: TTest;
begin
Result := TTest.Create;
end;
constructor TTestDictonary.Create;
begin
inherited Create([doOwnsValues]);
end;
end.