Hello.
In Pascal, there's no garbage collector. It means that what you have created, allocated, must be destroyed, unallocated.
- each New(pRec) must have a corresponding Dispose(pRec).
- each Create must have a corresponding Free, or even better FreeAndNil(oMyFCreate) if its allowed where you are coding it.
How to make \ let it simple?
With a variant of the Hungarian method which explains, if you should destroy the object where you are using it, or if you shouldn't destroy it because it has to be destroyed "in the distance", somewhere else! That's all.
Globally, the rule of thumb is that you have to free the allocated memory in the same namespace, closure, call stack level, etc..., as the one where you created it, allocated it.
Two possibilities:
- you declare your oMyFo object in same the namespace where it has been created, to remind you, that you'll have to destroy it there too. For example: F
oMyFoo is created in your OnFormCreate and you destroy it in your OnFormDestroy. Or your
oMyFoo is created in one method and destroyed in the same method.
- now, sometimes you create an object in one place and must destroy it in another place; or you use it in a place where it should not be destroyed. In this case you write your object
o_myFoo: : TMyFooObject or
frm_Foo: TFrmFoo, or
btn_Foo: TButton.
➔ So, if o
_myFoo is a parameter of a method, it reminds you that you must not destroy it in that method! Same approach: if you declare a Fo
_myFoo field, it means that your field will receive an instance of a TMyFooObject. Well, in accordance with this convention, it means that this instance could be passed as a parameter (to the constructor for example), or could be created in the constructor itself.
Reminder: • in Pascal, finding where you have created an object is always simple, easy: that's where you have to start using it . • What is clever is to understand, to remember, where it must be destroyed: where you'ra actually coding, where you're using it ? Or alternatively, somewhere else, "in the distant"? I come back to the previous example. Let's say you have a Fo
_myFoo field in your Form, and that you have created an instance of TMyFooObject in a method of this Form. What can you deduce from this? You can deduce from this conventio that Fo
_myFoo should not be destroyed in your Form even if that's where you created it. No, Fo
_myFoo should be destroyed elsewhere: for example, in a TfpList that has its OwnsObjects = true; a list, to which you've added the Fo
_myFoo; a list that has the responsibility to destroy that Fo
_myFoo.
Amho, if you code with this convention and always monitor the memory release, coding with Lazarus is no more complicated than with a language that has a garbage collector.