假设我有以下记录:
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()
帮助。谢谢
发布于 2015-04-24 22:05:15
如果你真的想在你的容器中存储指针,那么你需要在某个时候分配内存。如果在容器仍然包含对该内存的引用时释放内存,则容器的引用是无用的。它被称为陈旧指针。总是,持有陈旧的指针意味着你的代码是有缺陷的。
在我看来,这里似乎没有必要使用指针。您可以像这样声明字典:
TDictionary<Integer, TTest>该容器保存您的记录的副本,因此自动管理生存期。
发布于 2015-04-26 02:44:30
我同意大卫的观点。我认为这里不需要指针。使用一个类和一个TObjectDictionary,你就可以创建任意多的视图,而且内存管理仍然很简单:一个TObjectDictionary拥有这些类,另一个TObjectDictionary或TList<>只是呈现不同数据的视图。
这是inspiration的一个单元。
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.https://stackoverflow.com/questions/29849329
复制相似问题