1

I am working in Delphi XE7. Currently we do a lot of this:

function TMyClass.Clone(): TMyClass;
begin
  Result := TMyClass.Create();
  // Copy values/settings from Self to Result
end;

Using it often looks like this:

if (x <> nil) then
  y := x.Clone()
else
  y := nil;

Playing around with it, in XE7 the following works just fine for 32 and 64 but if Self is nil or a valid object instance:

function TMyClass.Clone(): TMyClass;
begin
  if Self = nil then
  begin
    Result := nil;
    Exit;
  end;
  Result := TMyClass.Create();
  // Copy values/settings from Self to Result
end;

Which then allows me to use the Clone() method more simply:

y := x.Clone();

My understanding of the compiler representation of object method calls leads me to think that this is OK, but I am leery of doing this as I cannot find the Embarcadero documentation saying that this kind of thing is officially supported.

Are object method calls with nil object instances officially supported?

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
MikeS85
  • 73
  • 6
  • 3
    Not *officially* (ie, not documented), but it is supported, within reason (see the duplicate question), otherwise `TObject.Free()` would not be allowed, since it checks `Self` for `nil` before calling `Self.Destroy()`, and `Free()` is heavily used in Delphi programming. – Remy Lebeau Jun 10 '19 at 23:51

0 Answers0