Jump to content
pyscripter

Are class vars supposed to be initialized?

Recommended Posts

I always thought class vars are supposed to be initialized.  See also this Stackoverflow question.

However in Alexandria 11.1 I got bitten by this:


 

type
  TMyComponent = class(TComponent)
  public
    class var GlobalInstance: TMyComponent ;
    constructor Create(AOwner: TComponent); override;
  end

constructor TMyComponent .Create(AOwner: TComponent);
begin
  inherited Create(AOwner);
  if Assigned(GlobalInstance) then
    raise Exception.Create('TMyComponent is a singleton.  You can only have one!');
  GlobalInstance := Self;
end;

 

When I added such a component to a data module in the 11.1 IDE an exception was raised.  It was working fine with 11.0.   Was I making a wrong assumption or is this an Alexandria 11.1 bug?


Update:  My stupid fault.  Actually the error has occurred when I closed one project and opened another one with the same component. I should set the GlobalInstance to nil in the desctructor, which I did not.   Even then the above approach is problematic if for instance you have have two projects in the same project group using this component.   I think this would create a problem.

 

Any better way of having a singleton component without causing issues in the IDE? 

Edited by pyscripter

Share this post


Link to post
5 minutes ago, pyscripter said:

When I added such a component to a data module in the 11.1 IDE an exception was raised.  It was working fine with 11.0.   Was I making a wrong assumption or is this an Alexandria 11.1 bug?

It's not documented at https://docwiki.embarcadero.com/RADStudio/Sydney/en/Fields_(Delphi).

 

PS. I am also in a couple of minutes will  install Delphi 11.1, hopefully I not going to see any new bugs.

Share this post


Link to post
Quote

Any better way of having a singleton component without causing issues in the IDE?

Look at TMessageManager class (System.Messaging unit). They implemented a class var for the default manager and a class property with a getter that initialize the call var if not already done, then return the instance.

  • Like 1

Share this post


Link to post

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

×