Warren
Warren

Reputation: 803

Please clarify @ and pointer and without them when adding object in delphi?

Please let me understand the following code.

procedure TForm1.Button1Click(Sender: TObject);
var
  Alist: TStringlist;
  i: integer;
begin
  Alist:=TStringlist.Create;
  Alist.Add('form1=form1');
  Alist.AddObject('form1',form1); //case 1
  Alist.AddObject('Pointer(form1)',Pointer(form1)); //case 2
  Alist.AddObject('Pointer(@form1)',Pointer(@form1)); // case 3
  Alist.AddObject('@form1',@form1); //case 4

  for i:=0 to Pred(Alist.Count) do // case getname
    Memo1.lines.add(Alist.Names[i]+' = '+ 
      inttostr(integer(Alist.Objects[i])));
  for i:=0 to Pred(Alist.Count) do // case getvalue
    Memo1.lines.add(Alist.ValueFromIndex[i]+' = '+
      inttostr(integer(Alist.Objects[i]))); 
end;

Case getname will generate:

form1 = 0
 = 13967624
 = 13967624
 = 4537296
 = 4537296

Case getvalue will generate

form1 = 0
orm1 = 13967624
ointer(form1) = 13967624
ointer(@form1) = 4537296
form1 = 4537296

Questions:

  1. Please clarify difference between case 1,2,3 and 4. especially case 2 and 3
  2. Can I always use any of them in all situations, ie, treat them always the same when adding object? if no, when should I use them differently?
  3. I know case getname, but why case getvalue can still have Names though I did not add like add('form1=form1') and the returned is short of the first character?

This is reproduced from Delphi 7.

Thanks so much for your help.

Upvotes: 1

Views: 198

Answers (3)

David Heffernan
David Heffernan

Reputation: 612954

1 and 2 are identical. 3 and 4 are identical.

An object reference already is a pointer, hence the equivalence of 1 and 2. The typecast in 2 is gratuitous.

For 3 and 4, @anything is a pointer and again, the typecast is gratuitous.

1 and 2 save the object reference in the list. 3 and 4 save a pointer to a variable holding the object reference.

The Names and Values properties are for working with items of the form 'name = value'. I don't think that is appropriate to the other part of your question.

Upvotes: 2

kludg
kludg

Reputation: 27493

Concerning the question #3 - Names and Values make sense only if the strings contain NameValueSeparator (= by default). Your strings (except the first) does not contain =. On Delphi XE your code outputs

form1 = 0
 = 32552528
 = 32552528
 = 5214864
 = 5214864
form1 = 0
 = 32552528
 = 32552528
 = 5214864
 = 5214864

which looks better.

Upvotes: 1

LeleDumbo
LeleDumbo

Reputation: 9340

  1. A class is already a pointer, so typecasting it to a pointer does nothing. @ is address-of operator in Pascal, the value is also a pointer, so again typecasting it to a pointer does nothing.

    form1 or pointer(form1) is the pointer to the form1 instance. @form1 or pointer(@form1) is the pointer to pointer to the form1 instance.

  2. Depends on what you want to store in the list

  3. Don't know about this one, have never used it before

Upvotes: 1

Related Questions