📜 ⬆️ ⬇️

Analog FreeAndNil with type checking

To combat the problem of "hanging" links to freed objects in Delphi, the SysUtils.FreeAndNil procedure is usually used. The FreeAndNil procedure frees an object and sets the variable to nil.
But I always did not like the fact that in this procedure there is not a typed parameter. And there you can pass not only an object, but also a string, a number, and any variable. Naturally, if you call with such an incorrect parameter, there will be problems. What is the most unpleasant problems can come out quite in another place.
I would like the compiler to control me, preferably at the compilation stage. But alas, to find a solution in which the compiler swore to try to call the procedure freeing and nullifying, I was not able to use the parameter incompatible with TObject. But I found a method in which such an attempt was detected at the execution stage during the first call. In general, it is better to see once. Here's the code for a safer analog to FreeAndNil.

unit CommonUnit ;
interface
type
TObjectHelper = class helper for TObject
public
procedure Free ( var Obj ) ;
end ;
implementation
procedure TObjectHelper . Free ( var Obj ) ;
begin
Assert ( Self = Pointer ( Obj ) , 'TObjectHelper. FreeSelf wrong type' ) ;
if Self <> nil then
begin
Pointer ( Obj ) : = nil ;
Destroy ;
end ;
end ;
end .

In the parameter, the variable reference is passed to the method, which must be reset. It is assumed that this will be the object itself whose method is called. For example: Obj.Free (Obj);
When this module is connected, the compiler will force you to replace all calls to the standard Free with the new Obj.Free (Obj). What turned out to be convenient for me. If the complete replacement of the standard Free is not required, you can change the method name in TObjectHelper.
As a result, we obtain a functionality similar to the standard FreeAndNil in the method that cannot be called for other types. Additional type control. And compiler tips on the places where the standard Free remained. In the cons, let there be a somewhat ugly challenge, the need to double-name the variable.
Yes, in new versions of Delphi this problem can be solved more beautifully, but I was limited to Delphi 2007.

')

Source: https://habr.com/ru/post/177431/


All Articles