Mega Code Archive

 
Categories / Delphi / OOP
 

Class Instance Counter

Title: Class Instance Counter Question: I want show you how to implement an instance counter in Delphi Object Pascal. It is possible to use it to find memory leaks. See the code and, please, send me suggestions. P.S: Sorry for my (bad) english... Answer: // --- Instance Counter Unit --- unit Unit1; interface uses SysUtils, Classes; type TOperation = (ooAdd, ooRemove, ooExtract); TInstanceCounter = class private { Private declarations } function GetCount: Cardinal; class function InstanceManager(value: TOperation): Cardinal; protected { Protected declarations } public { Public declarations } constructor Create; destructor Destroy; override; published { Published declarations } property InstanceCount: Cardinal read GetCount; end; implementation // --- TInstanceCounter ------------------------------------------------------- constructor TInstanceCounter.Create; begin inherited; InstanceManager(ooAdd); end; destructor TInstanceCounter.Destroy; begin InstanceManager(ooRemove); inherited Destroy; end; function TInstanceCounter.GetCount: Cardinal; begin Result := InstanceManager(ooExtract); end; {$J+} class function TInstanceCounter.InstanceManager(value: TOperation): cardinal; const X: Cardinal = 0; begin if value = ooAdd then Inc(X) else if value = ooRemove then begin if X 0 then Dec(X); end; Result := X; end; {$J-} initialization // finalization if TInstanceCounter.InstanceManager 0 then Beep; end. // ---------------------------------------