Delphi t使用指针的字典
假设我有以下记录:Delphi t使用指针的字典,delphi,delphi-xe2,Delphi,Delphi Xe2,假设我有以下记录: type TTest = record test1 : TTest1; test2 : TTest2; test3 : TTest3; end; pTTest = ^TTest; TDictestDictionary = TDictionary<integer,pTTest>; testDictionary : TDictestDictionary 或者需要初始化pValue
type
TTest = record
test1 : TTest1;
test2 : TTest2;
test3 : TTest3;
end;
pTTest = ^TTest;
TDictestDictionary = TDictionary<integer,pTTest>;
testDictionary : TDictestDictionary
或者需要初始化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()
TDictionary<Integer, TTest>
但是我如何编写getFTest()setFTest()
救命啊。
谢谢如果您真的想在容器中存储指针,那么您需要在某个时候分配内存。如果在容器仍然包含对该内存的引用时取消分配内存,则容器的引用是无用的。它被称为过时指针。通常,持有过时的指针意味着您的代码有缺陷 在我看来,这里似乎没有必要使用指针。您可以这样声明字典:
Type
myClass = class(TObject)
private
FTest : TDictestDictionary ;
public
property propFTest : TDictestDictionary read getFTest() write setFTest()
TDictionary<Integer, TTest>
t词典
该容器保存您记录的副本,因此自动管理生存期。我同意David的说法。我看这里不需要指针。使用一个类和一个
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.
单元测试;
接口
使用
系统、泛型、集合;
类型
TTest1=类
结束;
TTest2=类
结束;
TTest3=类
结束;
TTest=类
测试1:TTest1;
测试2:TTest2;
试验3:test3;
构造函数创建;
毁灭者毁灭;推翻
结束;
TTestDictory=类(TObjectDictionary)
公众的
构造函数创建;
功能测试:TTest;
结束;
实施
{TTest}
构造函数test.Create;
开始
继承;
test1:=TTest1.Create;
test2:=TTest2.Create;
test3:=TTest3.Create
结束;
析构函数t测试Destroy;
开始
测试1.免费;
测试2.免费;
测试3.免费;
继承;
结束;
{TTestDictonary}
函数TTestIctory.AddTest:TTest;
开始
结果:=TTest.Create;
结束;
构造函数TTestIctory.Create;
开始
继承的Create([doOwnsValues]);
结束;
结束。
但你到底为什么要存储指针?@Jens,因为复制记录可能会浪费时间,而且很难维护?想象一下,您可以将记录存储在一个普通数组中,并通过使用指针生成所需的视图。是的,您必须使它们与这些视图保持同步,但您也必须对具有记录副本的视图进行同步。@JensBorrisholt不带指针代码,如testDictionary[1]。test1=…
将创建记录副本,并且不会影响字典中的值。在这种情况下,您需要存储原因的记录指针,而不需要使用类和TObjectDictionary。这使得内存管理更容易,并给你指针的能力。为什么要使用类呢?这肯定是记录吗?记录不需要使用指针。没有我答案中类型的指针。正确,但在您的示例中,您不能直接使用列表中元素的属性。是的,您可以。使用列表
属性。如果该属性在Tlist yes中显示。