In Delphi 7, why can I assign a value to a const?

前端 未结 4 671
离开以前
离开以前 2020-12-01 14:32

I copied some Delphi code from one project to another, and found that it doesn\'t compile in the new project, though it did in the old one. The code looks something like thi

4条回答
  •  情书的邮戳
    2020-12-01 15:03

    Like Barry said, people took advantage of consts; One of the ways this was used, was for keeping track of singleton instances. If you look at a classic singleton implementation, you would see this :

      // Example implementation of the Singleton pattern.
      TSingleton = class(TObject)
      protected
        constructor CreateInstance; virtual;
        class function AccessInstance(Request: Integer): TSingleton;
      public
        constructor Create; virtual;
        destructor Destroy; override;
        class function Instance: TSingleton;
        class procedure ReleaseInstance;
      end;
    
    constructor TSingleton.Create;
    begin
      inherited Create;
    
      raise Exception.CreateFmt('Access class %s through Instance only', [ClassName]);
    end;
    
    constructor TSingleton.CreateInstance;
    begin
      inherited Create;
    
      // Do whatever you would normally place in Create, here.
    end;
    
    destructor TSingleton.Destroy;
    begin
      // Do normal destruction here
    
      if AccessInstance(0) = Self then
        AccessInstance(2);
    
      inherited Destroy;
    end;
    
    {$WRITEABLECONST ON}
    class function TSingleton.AccessInstance(Request: Integer): TSingleton;
    const
      FInstance: TSingleton = nil;
    begin
      case Request of
        0 : ;
        1 : if not Assigned(FInstance) then
              FInstance := CreateInstance;
        2 : FInstance := nil;
      else
        raise Exception.CreateFmt('Illegal request %d in AccessInstance', [Request]);
      end;
      Result := FInstance;
    end;
    {$IFNDEF WRITEABLECONST_ON}
      {$WRITEABLECONST OFF}
    {$ENDIF}
    
    class function TSingleton.Instance: TSingleton;
    begin
      Result := AccessInstance(1);
    end;
    
    class procedure TSingleton.ReleaseInstance;
    begin
      AccessInstance(0).Free;
    end;
    

提交回复
热议问题