Please give me some food for your mind about DELPHI pointers!
No, of course I read the mat part and worked with them (not fully understanding their nature) but why?
type TMyRec = class
s: string;
n: integer;
end;
var MyRec: TMyRec;
PRec: ^ TMyRec;
begin
// But MyRec is now null, which memory area can PRec start to refer to?
PRec: = @ MyRec;
PRec ^ .S: = 'Data string'; // Using the pointer, the string field of the record is changed
PRec ^ .N: = 256; // Changing the numeric record field using the pointer
end;
Everything is super, everything is great and works. But why bother if the next entry also works great?
var MyRec: TMyRec;
begin
MyRec: = TMyRec.Create;
MyRec.S: = 'Data string';
MyRec.N: = 256;
end;
In general, I have a bunch of questions on pointers that I can’t even formulate
I would be grateful for any information that explains why pointers are needed in everyday life
Answer 1, authority 100%
A pointer synonym is link.
There is memory, there is a reference to memory.
When passing TClass
in the procedure, a pointer (reference) to the object will still be passed, not the object itself.
When transferring record
without a pointer, the entire piece of memory will be transferred to the procedure, not a reference, that is, the complete structure.
The pointer is inherited from Pascal even before OOP, that is, when there were no classes yet.
In Pascal, there are no classes like TList, and in order to do something similar, you need to fence your garden:
TList = record
S: string;
Next: pointer;
prev: pointer;
end;
PList = ^ TList
That is, pointers are needed mainly for record
and for compatibility with Pascal
Answer 2, authority 90%
Let’s stop at
// But MyRec is null now
and
Everything is great, everything is great and works.
The local variable MyRec
before assignment is not nil
, but has an arbitrary value (garbage). You are just in luck, because in the following lines you write to an arbitrary memory area, and the consequences of this may be the most unexpected.
Remember in Sudden Access Violation Delphi 10.1 Berlin I changed your code
try
Props: = getProps;
...
finally
Props.Destroy;
end;
taking the assignment out of try
Props: = getProps;
try
...
finally
Props.Free;
end;
The meaning of the line assigning the value Props
outside the try / finally
block is that in case of an exception, inside getProps
, inside finally
the code will not hit, and there will be no attempt to free the memory pointed to by the uninitialized local variable Props
.
Another correct option:
Props: = nil;
try
Props: = getProps;
...
finally
Props.Free;
end;