Below is a simple example of using pointer in delphi.
Type
TRecord1 = Record
field1 : String;
end;
procedure TForm1.Button2Click(Sender: TObject);
var
Rec : TRecord1;
Ptr: ^TRecord1;
begin
Rec.field1:= 'field1';
Ptr := @Rec;
memo1.Lines.Add (Ptr^.field1);
memo1.Lines.Add (Ptr.field1); // it also works.
end;
In such case, Ptr^ and Ptr both work. It seems delphi is to allow user more flexibility in pointing to the value. But just by reading the two lines, they are syntactically different and may mean differently. In such case both work. But my question is:
- how can a user know in other situations where ^ can or can not be
omitted or, where with ^ or without ^ means the same or differently? - What are those situations ? Examples will be appreciated.
- Why? (Optional)
Thanks a lot in advance.
A plain
Pointerdoesn’t have any fields or properties, so ignoring Delphi’s smarts, thePointer.Fieldsyntax doesn’t make sense. Because of that there can’t be a conflict betweenPointer^.FieldandPointer.Field, simply because the plain.syntax is meaningless if you don’t dereference the pointer.If the type pointed to by the pointer doesn’t have any fields you have to use the
^syntax. That is, when the pointer is a pointer to a basic type, or is an untyped pointer.Class instance references (what most people would call "objects") are also pointers in Delphi, I assume the syntax was introduced to make working with Pointers less verbose and more like using classes. It’s also harmless, because as mentioned above, the compiler can’t get it wrong.
I personally prefer the
^.syntax, because it makes it clear I’m working with a pointer and not a record or class.