What are rules for whether or not using ^ to point to value?
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:
- 开发者_JAVA百科
- 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.
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.
A plain Pointer
doesn't have any fields or properties, so ignoring Delphi's smarts, the Pointer.Field
syntax doesn't make sense. Because of that there can't be a conflict between Pointer^.Field
and Pointer.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.
Why? (Optional)
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.
The only difference is that
Ptr1 := Ptr2
is not equal to
Ptr1^ := Ptr2^
The first line will make Ptr1 and Ptr2 to point to the same memory area, the second will assign the value pointed to by Ptr2 to the "variable" pointed to by Ptr1.
For this reason I believe allowing the Ptr.Field value syntax should be a bug, because even if no ambiguity may arise from the compiler side, it introduces a lazy way of writing code, that could backfire in situations like those above.
ptr.property is never valid and distinctly different from ptr^.property so Delphi allows you to leave out the ^. if ptr is not typed (or is a basic datatype) then ^ is always required.
It is very simple. If the use of ptr.field is UNambiguous, i.e. if it can't have any other meaning than ptr^.field, the ^ can be omitted.
But only then. In cases where omitting the ^ creates an ambiguous construct (i.e. where it could have different meanings), it can't be omitted.
精彩评论