I am trying to wrap my head around memory management in FPC/Lazarus and need to ask some questions about Free, Nil and Destroy and the side effects of TSomeObject.Create where there is no explicit Destroy(ing).
I take it that Free reclaims the space used by an object, and Nil sets the pointer that equates to the TSomeObject to zero (ensures that it doesn't point to anything). I also take it that when a procedure exits the memory allocated to the variables declared in it are it reclaimed, but items they were created to point to will hang around unless actively freed.
Does the Destroy procedure imply the existence of a Destructor procedure that is meant to Free, Nil and Destroy the objects create by the TSomeObject, TComponent or whatever?
Also are these scenarios involving TSomeObject.Create.
procedure TCreateObject.UseMemory;
var
anObject: TSomeObject;
begin
anObject := TSomeObject.Create;
end;
Memory will not be freed until application terminates?
procedure .TCreateObject.UseMemorySelf;
var
anObject: TSomeObject;
begin
anObject := TSomeObject.Create(self);
end;
Memory will not be freed until self object if destroyed?
procedure .TCreateObject.UseMemoryApplication;
var
anObject: TSomeObject;
begin
anObject := TSomeObject.Create(Application);
end;
Memory will not be freed until application terminates?
procedure .TComponentCreate.UseComponent;
var
anObject: TComponent;
begin
anObject := TComponent.Create(AOwner);
end;
Memory will not be freed until AOwner is destroyed.
Last bit.
Say in the main unit I have
var
objectArray = array[1..10] of TSomeObject;
and throughout the program I do stuff like:
procedure TThisObject.CreateSomeObjects
var
someObject: TSomeObject;
begin
someObject := TSomeObject.Create;
objectArray[next] := someObject;
next := next+1;
end;
When that units ends I will have to so something like
for i := 0 to TSomeObjectTypes.Count - 1 do
begin
if Assigned(objectArray[i+1]) then
objectArray[i+1].Destroy
end;
Right?
A lot of the stuff I do entails components placed on some forms, so I take it that when the forms are closed and destroyed, the memory they use will be freed, but that means that if any of the units and components they use create objects which are not destroyed by the components that create them they will lurk around till the application itself terminates?
Are there some things which are automatically freed, like those so labelled reference-counted objects like TAnsiStrings etc?
I am looking forward to interesting times indeed