[英]Delphi - Confused about memory allocation in TDictionary
In Delphi XE6, I have a TDictionary called WordDict which holds instances of TWordRec. 在Delphi XE6中,我有一个名为WordDict的TDictionary,它包含TWordRec的实例。 Definitions are: 定义是:
WordDict: TDictionary<string, TWordRec>;
...
type
TWordRec = class
public
RemoveAlways: Boolean; // Is this CORP LLC, etc?
RemoveRestricted: Boolean;
Replace: Boolean;
ReplaceWith: string;
Constructor Create(B1, B2, B3: Boolean; S1: String); overload;
end;
When I create and load the Dictionary.... 当我创建并加载字典....
WordDict := TDictionary<string, TWordRec>.Create;
WordDict.Add('CO', TWordRec.Create(True, False, False, ''));
WordDict.Add('CORP', TWordRec.Create(True, False, False, ''));
...
I am running into a memory leak, and using AQTime, its showing each occurrence of my TWordRec is "leaking" memory. 我遇到内存泄漏,并使用AQTime,它显示我的TWordRec每次出现“泄漏”内存。 If I am creating the WordDict entries as TWordRec, how do I dispose of them after they are loaded? 如果我将WordDict条目创建为TWordRec,如何在加载后处置它们? Do I dispose of them, since isn't this just a pointer in the dictionary to the actual object? 我是否处理它们,因为这不仅仅是字典中指向实际对象的指针吗?
Do I dispose of the TWord immediately after loading? 装载后我是否立即丢弃TWord? Do I delete all the entries from my Dictionary ONLY when the app closes down? 当应用关闭时,我是否仅删除词典中的所有条目? I obviously don't understand WHY I am getting a memory leak on TWordRec, so I don't know how to resolve it... 我显然不明白为什么我在TWordRec上遇到内存泄漏,所以我不知道如何解决它...
Thanks! 谢谢!
You aren't getting a memory leak on TWordRec
, rather the TDictionary
isn't behaving as you'd expect. 您没有在TWordRec
上获得内存泄漏,而TDictionary
的行为并不像您期望的那样。 The standard TDictionary
class doesn't have any mechanism for object ownership. 标准的TDictionary
类没有任何对象所有权机制。 If you change your container class to TObjectDictionary
and create it with the doOwnsValues
option set, it will automatically free the owned objects on destruction which is the behaviour you are expecting. 如果将容器类更改为TObjectDictionary
并使用doOwnsValues
选项集创建它,它将自动释放所拥有的对象,这是您期望的行为。
The alternative is to iterate through the items freeing each object in your TDictionary
instance before finally freeing the TDictionary
object. 另一种方法是在最终释放TDictionary
对象之前迭代释放TDictionary
实例中每个对象的项。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.