Gallery
Software
Music
Programming
Archive
Saturday, Feb 23 Week 8

Safely destroy objects, threads and memory

Safe means checking that reference is not nil,- also clearing reference before destroying objects. Try..except used to avoid visual exception. Based on FreeAndNil procedure from SysUtils unit. Examples for objects, threads and allocated memory (pointers).

procedure safeDispose(var p);
procedure safeFree(var obj);
procedure safeTerminate(var thrd);

implementation

procedure safeDispose(var p);
var q:pointer;//clear reference before dispose data
begin
try
if pointer(p)=nil then exit;
q:=pointer(p);
pointer(p):=nil;
dispose(q);
except
pointer(p):=nil;
end;
end;

procedure safeFree(var obj);
var p:TObject;//clear reference before destroy object
begin
try
if TObject(obj)=nil then exit;
p:=TObject(obj);
TObject(obj):=nil;
p.free;
except
TObject(obj):=nil;
end;
end;

procedure safeTerminate(var thrd);
var p:TThread;//clear reference before terminate thread
begin
try
if TThread(thrd)=nil then exit;
p:=TThread(thrd);
TThread(thrd):=nil;
p.terminate;
except
TThread(thrd):=nil;
end;
end;

//Examples
//safeFree(obj); //Instead of obj.free;
//safeDispose(p); //Instead of dispose(p);
//safeTerminate(thread); //Instead of thread.Terminate;

Related pages of Safe destruction of objects

Programming
Delphi examples
Delphi programming