Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How objects are initialized in delphi XE vs XE4

I have a class

type
  TLoadOption = class
  private
    FAutoSearch: Boolean;
  public
    property AutoSearch: Boolean read FAutoSearch write FAutoSearch;
  end;

In one of the functions i am creating the object of the class in stack

procedure MyView.InitializeForm(const aMsg: MyMsg);
//---------------------------------------------------------------------------
var
  Options: TLoadOption;
begin

  if aMsg.OptionalObject <> nil then
   Options := aMsg.OptionalObject as TLoadOption;

  if Assigned(Options) and Options.AutoSearch then
    DoRefresh;
end;

I am not passing anything in aMsg so ideally Options is not set.

In Delphi XE by default Options is set as nil and so this DoRefresh is not called but when i execute the same code in Delpi XE4 the options is initialized with some random value and AutoSearch becomes true always and it results in calling this DoRefresh function which is undesired.

I am wondering if there are any compiler options that set default values to uninitialized variable. My only solution as of now is like this

 procedure MyView.InitializeForm(const aMsg: MyMsg);
    //---------------------------------------------------------------------------
    var
      Options: TLoadOption;
    begin
      Options := nil;

      if aMsg.OptionalObject <> nil then
       Options := aMsg.OptionalObject as TLoadOption;

      if Assigned(Options) and Options.AutoSearch then
        DoRefresh;
    end;

is this a correct way?

like image 201
Jeeva Avatar asked Mar 07 '14 10:03

Jeeva


1 Answers

A local class is not initialized. You need to set it to nil before testing its assignment.

See Are delphi variables initialized with a value by default?.

Only local reference-counted variables are initialized (example: String,dynamic arrays,interface,variants).

If you are targeting mobile platforms, where ARC (automatic reference counting) is introduced, classes are reference counted though. See Automatic Reference Counting in Delphi Mobile Compilers.

like image 67
LU RD Avatar answered Sep 28 '22 05:09

LU RD