Must free TRegEx object after TRegEx.Create?
Asked Answered
R

1

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?

Rubstone answered 11/8, 2017 at 21:37 Comment(0)
K
14

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).

Kerman answered 11/8, 2017 at 21:42 Comment(5)
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.Adila
IIRC, there are some records in the RTL that do use static Create methods that are not declared with the constructor keyword.Kerman
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.Adila
Naming them Create is a bad idea too. It makes the reader think they are constructors.Consideration
Thanks for the clarification!Rubstone

© 2022 - 2024 — McMap. All rights reserved.