Is there a benefit in using old style `object` instead of `class` in Delphi?

前端 未结 4 1538
刺人心
刺人心 2020-12-31 15:31

In Delphi sane people use a class to define objects.
In Turbo Pascal for Windows we used object and today you can still use

4条回答
  •  天命终不由人
    2020-12-31 16:04

    Object was not the Delphi 1 method of setting up objects; it was the short-lived Turbo Pascal method of setting up objects, which was replaced by the Delphi TObject model in Delphi 1. It was kept around for backwards compatibility, but it should be avoided for a few reasons:

    1. As you noted, it's broken in more recent versions. And AFAIK there are no plans to fix it.
    2. It's a conceptualy wrong object model. The entire point of Object Oriented Programming, the one thing that really distinguishes it from procedural programming, is Liskov substitution (inheritance and polymorphism), and inheritance and value types don't mix.
    3. You lose support for a lot of features that require TObject descendants.
    4. If you really need value types that don't need to be dynamically allocated and initialized, you can use records instead. You can't inherit from them, but you can't do that very well with object either so you're not losing anything here.

    As for the rest of the question, there aren't all that many speed benefits. The TObject model is plenty fast, especially if you're using the FastMM memory manager to speed up creation and destruction of objects, and if your objects contain lots of fields they can even be faster than records in a lot of cases, because they're passed by reference and don't have to be copied around for each function call.

提交回复
热议问题