Is the procedure for safe use of the object after the release of the object?

I wrote a simple class as follows:

TMyClass = class procedure MyProcedure(Sender : TObject); end; 

I execute "MyProcedure" in which I never refer to "I" after the release of the object:

 var MyObj : TMyClass; ProcOfObj : TNotifyEvent; begin MyObj := TMyClass.Create; try ProcOfObj := MyObj.MyProcedure; finally MyObj.Free; end; ProcOfObj(Self); end; 

This works, but I am wondering if this practice is safe or may cause some problems.

+7
delphi
source share
3 answers

If MyProcedure and any methods it calls do not really reference the Self instance, then you will not run into runtime errors. However, this is a risky game. All that is required is to make some changes in the future, not knowing about this problem, and introduce the territory of behavior undefined. You may encounter runtime errors, or you may not. And the compiler will not save you.

You do not want to risk it. Therefore, since your method does not reference the instance, do not make it an instance method.

 type TMyClass = class class procedure MyProcedure(Sender : TObject); end; 

Instead, make a class method. This way you avoid the risk and the compiler will save you if at some point in the future you try to access the instance.

+10
source share

This is definitely not a safe practice. As soon as the procedure tries to access a member variable of its own object, you will receive access violations. Do not put such a trap in your code. You or your team members sooner or later get into it.

+3
source share

It is not safe, and it breaks the encapsulation of the code.

Imagine if eventually your implementation of TMyClass.MyProcedure changes and starts to refer to self ? You will get a segmentation error.

In addition, you are going against OOP, as you must know the implementation details of the method you are calling to use it.

If you want your method not to refer to a self pointer, declare the method as a static member.

+2
source share

All Articles