Post by Ryan JosephI had no idea you could do that!
Obviously, it speaks high of your abilities ;)
You've been able to accomplish your tasks without use of hacks (of any
kind), playing strict by the rules.
Iâm totally confused now. Since when was it ok to call methods on nil
Post by Ryan Josephobjects? According to this test not only can you call methods on nil
objects but it calls the method statically (like a class method), i.e the
test prints âDoThisâ. How is that possible?
From the low-level (virtual/physical memory, CPU) perspective you can do
that at any time on either nil-ed or uninitialized object as long as the
method doesn't try to access and invalid memory.
The example (compiled for i386 and not using -CR works as expected)
type
TRobust = class(TObject)
public
v : Integer;
function Max(a,b: Integer): Integer;
end;
function TRobust.Max(a,b: Integer): Integer;
begin
if a>b then Result:=a
else Result:=b;
end;
var
r : TRobust;
begin
r := nil;
writeln(r.Max(5,10));
end.
However such behavior, would be RTL specific - it's all about how the
compiler would generate such call. If it would attempt to access any field
(i.e. VMT) related to the instance of the object itself (rather than the
class), there's a high chance it would fail.
And that's why having -CR enabled during development is generally a very
good idea.
From high-level (OOP) such actions are not welcomed (and are enforced using
-CR in case of FPC).
In order to have robust, maintainable and portable (to either other
platform or even language) a developer should respect high-level rules and
never depend on low-level rules to be the same on any platform.
thanks,
Dmitry