The next article on dynamic arrays in Delphi says that you allocate a dynamic array using the SetLength() function.
myObjects : array of MyObject; ... SetLength(myObjects, 20);
http://delphi.about.com/od/beginners/a/arrays.htm
This seems like a memory leak for me:
The question is , if SetLength() is the C ++ equivalent of MyObject *obs = new MyObject[20] , then the arrays are just pointers, so the Delphi parameter myObjects sets the value nil to the same as setting obj = NULL in C ++? Ie, is this a memory leak?
EDIT : I understand that David answers that the compiler manages memory for dynamically allocated arrays. I also understand from his answer how the compiler manages memory for regular class instances (hence using myObj := MyObject.Create and myObj.Free , myObj := nil , etc.). In addition, since Delphi classes (not records) are always allocated on the heap (Delphi uses a type of reference / pointer system), does this mean that all objects in a dynamic array (with automatic memory management) should still be associated with memory managed me? For example, does the cause cause a double release of the result?
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;
source share