I’ve looked at many questions and resources which deal with the “Self” variable in an Object, but everyone says something different.
For example, in this question: Delphi Self-Pointer usage
the highest rated answer to the question appears to be wrong. Pointer(Self) does not point to the object which contains it, and cannot be used to pass references from inside the object.
I’ve tried doing this:
Type
myobject = class
PSelf: Pointer;
End;
Var
Obj: myobject;
Procedure RunProgram;
Begin
Obj := myobject.create;
Obj.PSelf := @Obj;
//Run the rest of the program
.
.
.
and for the most part, this has worked just fine.
My question is: is this a good coding practice? Can the “PSelf” variable be expected to point to the object for the duration of the program’s execution?
I recently came across a bug where “PSelf” had stopped pointing to it’s containing object, and I’m wondering if objects ever get shuffled around in the heap, or whether the memory had been corrupted.
Edit:
There is some instance in which using the “Self” variable didn’t work for me, and now I cannot duplicate it. So this whole question is pointless, as is my technique of using a ‘PSelf’ variable. Sorry about that.
And as Ken pointed out, the link above has a correct answer 🙂
I think you’re misunderstanding what
Selfis, and how object references work in Delphi.A variable containing an instance of a class is already a pointer to that object instance. The Delphi compiler just allows you to leave out the dereference operator (
^) as a convenience.Delphi also allows the shorthand of not using the dereference operator when accessing members or properties of the object instance. Again, the following code is actually equivalent:
From the Delphi documentation:
Selfis an automatically declared property that points to the current instance of the object. In other words, it’s automatically available inside the code that implements that class to reference the current instance of the object. This allows you to have multiple instances of the same object:Note that
Selfis only valid in the code that implements the class. It’s available and valid inTMyObject.GetMyIntegerandTMyObject.SetMyIntegerabove (the only implemented code in my example), and always refers to the current instance.There’s no need to keep track of the addresses of
Self, as the variable referencing that object instance isSelfinside methods of that object instance. It’s only valid inside that instance of the object, and always refers to that object instance. So in your code example,PSelfis just wasted space –myobjectalready contains a pointer to itself, and that pointer is automatically available in methods ofmyobject: