Search code examples
delphiooprtti

How to FREE nested (object type) field classes?


TBaseClass = class
public
  destructor Destroy; override;
end;

TFirstClass = class(TBaseClass)
  FMyProp: string;
end;

TSecondClass = class(TBaseClass)
  FMyFirstClass: TFirstClass;
end;

I need to implement a DESTRUCTOR that can be able to find all (object type) fields from the same base class and give a Free on it to avoid all those memory leaks.

Why? Because FMyFirstClass be can created or not, that depends on the flow of my app and I can't garantee when it will be created to Free it, neither do want to fill all destructors with a NIL check kind of code, because i have a lots of fields like that.

I'm trying to use the new RTTI to get all fields based on TBaseClass, but I can't get the instance of the object-field and I'm out of ideas.

Am I going to the right way? What you suggest to do?


Solution

  • Calling Free has no effect on a nil instance. It's deliberately designed that way. Your destructors should call Free on any fields of object types which it logically owns, irrelevant of whether the object has been constructed or not.