So, I made a gist...

So, I made a gist...

Running the "Example" procedure within it writes "No runtime exception!" to the console.

I feel like this is weird. If I tried to access a field on the class, I would get the exception.

I understand why it happens (I think), but I still felt that it was a bit curious.
https://gist.github.com/undreren/1d4f4562c9f6099098d7c0ea4898b80c

Comments

  1. that gets translated to

    procedure ttest_test(self: pointer);
    begin
    writeln('xxx');
    end;

    and called

    ttest_test(nil);

    all good (;

    ReplyDelete
  2. Dorin Duminica is right. As long as you don't access member variables the code will run just fine. It would crash if TTest.Test read the string from a member variable instead of using a constant value.

    ReplyDelete
  3. Dorin Duminica Is that how TRttiContext works?

    ReplyDelete
  4. What has this code to do with TRttiContext?

    FWIW what you expected is what managed languages like C# or Java do by raising null reference exceptions on the caller side.

    ReplyDelete
  5. Stefan Glienke What I meant with the TRttiContext comment was that you are advised not to "create" an instance. Instead you just need to declare a variable, and then start using it.

    I don't know why, but It didn't occur to me to look up the definition. Now I see that it's just a record.

    But yeah, I expected the Java/C# behavior.

    ReplyDelete
  6. Kasper Brohus Allerslev No, that's something else altogether. RTTI contexts are not related to this issue at all.

    Ask yourself what happens though when you call Free on a reference that is nil. Every single time you call Free you rely on this behaviour. That is that an instance method can safely be called on a nil reference so long as the instance pointer is not de-referenced.

    ReplyDelete
  7. Kasper Brohus Allerslev isn't TRttiContext a record type?

    ReplyDelete
  8. TRttiContext is a record type that has mechanic to ensure its initialization when using it. See http://blog.barrkel.com/2010/01/delphi-2010-rtti-contexts-how-they-work.html

    ReplyDelete
  9. Jeroen Wiert Pluimers It is. That's what I wrote in my previous comment :)

    ReplyDelete

Post a Comment