I've written a simple class like this:
TMyClass = class
procedure MyProcedure(Sender : TObject);
end;
I'm executing "MyProcedure", in which I never refer to "Self", after the object has been freed:
var
MyObj : TMyClass;
ProcOfObj : TNotifyEvent;
begin
MyObj := TMyClass.Create;
try
ProcOfObj := MyObj.MyProcedure;
finally
MyObj.Free;
end;
ProcOfObj(Self);
end;
It works but I'm wondering if it's a safe practice or if it could cause some issue.
If MyProcedure
, and any methods that it calls, really do not refer to the Self
instance then you won't encounter runtime errors. However, it is a risky game to play. All it takes is for you to make some future change to the code, without being aware of this issue, and you enter undefined behaviour territory. You may encounter runtime errors, or you may not. And the compiler won't save you.
You don't want to risk that. So, since your method does not refer to an instance, don't make it be an instance method.
type
TMyClass = class
class procedure MyProcedure(Sender : TObject);
end;
Instead make it a class method. That way you avoid the risk, and the compiler will save you if at some point in the future you do attempt to refer to the instance.
This is definitely not safe practice. As soon as the procedure attempts to access a member variable of its own object you will receive access violations. Don't place such a trap in your code. You or your team members will fall into it sooner or later.
It is not safe and it breaks code encapsulation.
Imagine if eventually your implementation of TMyClass.MyProcedure
changes and starts to reference self
? You will get a segmentation fault.
Also, you are going against OOP, since you must have knowledge of the implementation details of the method you are calling to make use of it.
If you want to enforce that your method does not reference a Self
pointer, declare the method as a static member.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With