Search code examples
arraysmultidimensional-arraydisposefreepascal

Disposing array of objects in Free Pascal


I'd like to create a two-dimensional array of TMyClass objects, considering that each of these objects contains an array of references to TMyClass, i.e.

type
    TMyClass = class
        MyArray: array[0..10] of TMyClass;
        constructor Create;
        destructor Destroy;
    end;

    TMyMatrix = array of array of TMyClass;

var
    matrix: TMyMatrix;

begin
    SetLength(matrix, 10, 10);
    (...) { matrix[i, j].Create; ? }

1) Will the array of references (MyArray) be automatically disposed (without affecting actual objects) while disposing of TMyClass object, or should I take care of it manually?

2) What about disposing the dynamic array of objects (matrix)? Free Pascal wiki says assigning nil to a dynamic array frees the memory where pointer points to, but I assume it is not going to call any destructors.


Solution

  • 1) Yes, if you free the TMyClass instance then MyArray will be freed because its reference count will drop to zero. An exception to this is if you globally reference this array elsewhere in the code, which shouldn't occur with good code design. The actual objects in the array will not be freed automatically (read on).

    2) No, resizing the array to zero, setting it to null or making its reference count zero will not automatically free any classes you are referencing in its elements. You need to do it yourself, by walking through the 2D array, and freeing each object properly.

    From the documentation, "Assigning nil to a dynamic array variable automatically frees the memory where the pointer pointed to.". That's all it does, so it will not actually touch your classes, only free the memory allocated to storing their references (which are pointers).

    Ref. http://wiki.freepascal.org/DYNAMIC_ARRAY