Reputation: 71
I have learnt that in Delphi I have to use try .. finally
to free the allocated object on the heap. In java I never do this because it's not my job but that's something that the garbage collector does. Also delphi hasn't ref count on windows and so I need to use the try finally. Is there an alternative?
Do I have to use interface or a particular class to avoid the guard? like
var a: ttest;
begin
a := ttest.create;
//do stuff
end;
Upvotes: 2
Views: 520
Reputation: 31453
You can use interfaces for some things, but fundamentally there is no getting around the fact that Delphi simply does not implement garbage collection or reference counting for regular objects in the legacy desktop compilers for Windows and OSX (it does use reference counting in the NextGen compilers for Android, iOS, and Linux***).
It is not practical to use interfaces for everything, so you simply have to get used to cleaning up after yourself. If you create an object, free it when you are done using it.
Now, there are all kinds of clever patterns you can come up with to tidy up, or work around, having to use a simple try/finally
block, but this ends up being a lot of work and you end up producing bulky, awkward code that does not flow with the style of the language. Invariably, you will also be using third party libraries, components, etc, and all of these will generally be written in a style common to most Delphi code.
To brutishly force an artificial memory management pattern on top of this will be far more work than simply doing it the "Delphi way", and will produce code that is difficult for other programmers to understand and work with. Just don't do it.
Smart pointers are one way to automate lifetime management. A good example implementation can be found here:
Delphi - smart pointers and generics TList
But this becomes a difficult pattern to generalize, particularly for objects with constructors taking a variety of parameter lists. An interface or a smart pointer implementation is usually a tool created to solve a specific type of problem. They aren't applied as a broad-brush solution to automatic memory management, and trying to shoehorn them into this role will make for a very difficult time indeed.
*** Since the time of this answer's writing, even Embarcadero have abandoned object ARC in the new compilers for similar reasons.
Upvotes: 10