Delphi class constructor for object initialization

I have developed a class and I need my object to be able to hold the "history" of what happened during the lifetime of the program.

type
 TPipelineSimulator = class
  private
   class var history: TStringList;
   class constructor Create;
   class destructor Destroy;
   //other code
  public
   class property bitHistory: TStringList read history;
   //other code
 end;

And the simple implementation is:

class constructor TPipelineSimulator.Create;
begin
 history := TStringList.Create;
end;

class destructor TPipelineSimulator.Destroy;
begin
 history.Free;
end;

The class TPipelineSimulator has a normal procedure (not class procedure) that adds strings to the history variable; in this way I can fill my stringlist and access it with this code:

for k := 0 to a.history.Count-1 do
  Memo1.Lines.Add(a.history.Strings[k]);

This is very useful because even if the object is created and then released (the usual Free inside try-finally) I still can access to the stringlist. I have two questions about class constructors and destructors.

  • The documentation says that constructors are inserted automatically by the compiler into the initialization section. The opposite happens with destructors. Does this mean that if I called var a: TPipelineSimulator; inside a button onclick procedure the class constructor for a is called when the program starts? Or just when I call the procedure for the first time?

  • In case of an exception (maybe by mistake I go out of bounds in the stringlist) do I risk a memory leak?

  • In point 2 I mean something like this. If the StringList is filled with 1 item each time, at the beginning the code below causes an out of bounds error a few times:

    showmessage(a.history.strings[10]);
    

    Despite that I can still access the stringlist and I has really wondering if this code is dangerous.


    1) Class constructors are executed with the initialization section of the unit in which the class is implemented - to be precise: immediately before the code in the initialization section. For the destructor it is the other way round. The initialization order of the units is determined by the compiler.

    The difference to the initialization/finalization section code is that class constructors/destructors are executed only if the class is actually used inside the program.

    2) As long as the class destructor is called, you don't get a memory leak (at least not from this stringlist).

    链接地址: http://www.djcxy.com/p/60262.html

    上一篇: NHibernate生成器

    下一篇: 用于对象初始化的Delphi类构造函数