[fpc-pascal] Implementing a true Singleton - Can we decrease the visibility of a method?

Marc Santhoff M.Santhoff at t-online.de
Thu Dec 14 04:39:30 CET 2006


Am Donnerstag, den 14.12.2006, 07:42 +1000 schrieb Steve Williams:
> Marc Santhoff wrote:
> > constructor TSingleton.create;
> > begin
> >         if not(assigned(s)) then
> >         begin
> >                 inherited;
> >                 (*... do initializations ...*)
> >                 s := self;
> >                 writeln('creating new singleton');
> >         end else begin
> >         	self := s; // <-- Danger, Will Robinson!
> >         end;
> > end;
> >   
> 
> This is where you lose memory.  TObject.NewInstance is implicitly called 
> before the constructor.  It allocates memory for the instance.  Now you 
> have lost track of that memory by overwriting Self.  Every time you call 
> TSingleton.Create, you lose memory.

Yes, that's what I feared.

> Override NewInstance as shown in 
> the link I listed previously in this thread for a solution that will not 
> lose memory.

Now I see, I should have read it earlier but missed it not following the
complete thread.

Thanks,
Marc





More information about the fpc-pascal mailing list