Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is a procedure of object safe to use after the object has been freed?

Tags:

delphi

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.

like image 741
Fabrizio Avatar asked Aug 16 '16 14:08

Fabrizio


3 Answers

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.

like image 101
David Heffernan Avatar answered Sep 30 '22 18:09

David Heffernan


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.

like image 23
Wosi Avatar answered Sep 30 '22 16:09

Wosi


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.

like image 32
Vinícius Gobbo A. de Oliveira Avatar answered Sep 30 '22 16:09

Vinícius Gobbo A. de Oliveira