【发布时间】:2014-02-28 03:57:55
【问题描述】:
下面关于 Delphi 中动态数组的文章说您使用 SetLength() 函数分配动态数组。
myObjects : array of MyObject;
...
SetLength(myObjects, 20);
// Do something with the array.
myObjects := nil;
http://delphi.about.com/od/beginners/a/arrays.htm
这对我来说似乎是内存泄漏:
问题是,如果SetLength()相当于C++中的MyObject *obs = new MyObject[20],那么数组就是指针,所以将Delphi的myObjects变量设置为nil与在 C++ 中设置obj = NULL?即,这是内存泄漏吗?
编辑:我从 David 的回答中了解到编译器为动态分配的数组管理内存。我也从他的回答中了解到,编译器确实为普通类实例管理内存(因此使用myObj := MyObject.Create 和myObj.Free、myObj := nil 等)。此外,因为 Delphi 类(不是记录)总是在堆上分配(Delphi 使用一种引用/指针系统),这是否意味着(自动内存管理的)动态数组中的所有对象仍然需要内存 -由我管理?例如,以下是否通过双重释放结果导致错误?
myObjects : array of MyObject;
...
SetLength(myObjects, 20);
for i := 0 to 19 do
begin
myObjects[i] := MyObject.Create;
end;
// Do something with the array.
// Before de-allocating it, if I *know* I am the only user of the array,
// I have to make sure I deallocate each object.
for i := 0 to 19 do
begin
myObjects[i].Free;
myObjects[i] := nil; // Redundant, but for illustrative purposes.
end;
myObjects := nil;
【问题讨论】:
标签: c++ arrays delphi pointers