了解 TList的内存分配
我必须存储一个可以在 Delphi 中轻松实现为记录的 TList(五个简单字段)。但是,我不清楚执行 TList
时会发生什么。
由于 R 是我创建 TList 的过程中的局部变量,因此我假设函数返回时将释放它的内存。这是否会在列表中留下无效的记录指针?或者列表是否知道分配时复制?如果是前者,我认为我必须使用 New() 和 Dispose() 手动管理 R 的内存,这是正确的吗?
或者,我可以通过简单地将字段声明为公共(甚至不用费心使它们成为正式属性)来将我的记录类型“提升”为类类型。这被认为可以吗,或者我应该花时间构建具有私有字段和公共属性的类吗?
I have to store a TList of something that can easily be implemented as a record in Delphi (five simple fields). However, it's not clear to me what happens when I do TList<TMyRecordType>.Add(R)
.
Since R is a local variable in the procedure in which I create the my TList, I assume that the memory for it will be released when the function returns. Does this leave an invalid record pointer in the list? Or does the list know to copy-on-assign? If the former, I assume I would have to manually manager the memory for R with New() and Dispose(), is that correct?
Alternatively, I can "promote" my record type to a class type by simply declaring the fields public (without even bothering with making them formal properties). Is that considered OK, or ought I to take the time to build out the class with private fields and public properties?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
简化:记录是数据块,默认情况下按值传递(即通过复制它们)。
TList
将值存储在 T 类型的数组中。因此,TList.Add(R)
将复制值R
到数组的Count
位置,并将Count
加一。无需担心内存的分配或释放。您通常不需要担心的更复杂的问题:如果您的记录包含字符串类型、接口类型、动态数组的字段,或者记录本身包含这些类型之一的字段,那么它不仅仅是一个只需复制数据;相反,使用 System.pas 中的 CopyRecord,这可确保正确更新引用计数。但通常您不需要担心这个细节,除非您使用
Move
来移动自己周围的位,或者执行类似的低级操作。Simplified: records are blobs of data and are passed around by value - i.e. by copying them - by default.
TList<T>
stores values in an array of type T. So,TList<TMyRecordType>.Add(R)
will copy the valueR
into the array at positionCount
, and increment theCount
by one. No need to worry about allocation or deallocation of memory.More complex issues that you usually don't need to worry about: if your record contains fields of a string type, an interface type, a dynamic array, or a record which itself contains fields of one of these types, then it's not just a simply copy of data; instead, CopyRecord from System.pas is used, which ensures that reference counts are updated correctly. But usually you don't need to worry about this detail unless you are using
Move
to shift the bits around yourself, or doing similar low-level operations.