9

I have seen several Delphi examples of TRegEx usage like the following one in Delphi 10.1.2:

try
  RegexObj := TRegEx.Create(REGEX_EXTRACTEMAILADDRESSES, [roIgnoreCase]); 
  MatchResults := RegexObj.Match(ThisPageText);
  while MatchResults.Success do
  begin
    slEmailAddressesOnThisPage.Add(MatchResults.Value);
    MatchResults := MatchResults.NextMatch();
  end;
except
  on E: ERegularExpressionError do
  begin
    // Todo: Log Syntax error in the regular expression
  end;
end;

So I wonder whether the TRegEx object must be explicitly freed after creation in such an example?

user1580348
  • 5,721
  • 4
  • 43
  • 105

1 Answers1

13

Only class objects that derive from TObject must be explicitly freed from memory after being created. TRegEx is a record instead, so it is released when it goes out of scope. TRegEx.Create is a constructor, but not one that creates a new object on the heap, just on the call stack, so there is nothing to free manually (there is no destructor defined for it).

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
  • 4
    As others have said in the past, Embarcadero calling such methods *constructors* (i.e. using the `constructor` keyword for them) is misleading, since there is no *destructor*. I would rather see them call those methods *initializers* and make them class functions returning a record of the given type. They should stop calling them constructors, as this question once again proves. – Rudy Velthuis Aug 11 '17 at 22:04
  • IIRC, there are some records in the RTL that do use static `Create` methods that are not declared with the `constructor` keyword. – Remy Lebeau Aug 11 '17 at 22:06
  • 6
    Yes, but that should be the norm, not the exception. They should never have been called *constructor*, IOW that keyword should simply never have been applicable to methods of records at all. – Rudy Velthuis Aug 11 '17 at 22:29
  • 6
    Naming them Create is a bad idea too. It makes the reader think they are constructors. – David Heffernan Aug 12 '17 at 04:43
  • Thanks for the clarification! – user1580348 Aug 12 '17 at 08:40