Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why Delphi objects that implement interfaces need to be reference counted?

In other words, why can't they be manually managed like a regular object? Or Did the Delphi designers just decided to use reference counting since it was needed for COM anyways?

like image 221
Daniel Santos Avatar asked Mar 05 '14 11:03

Daniel Santos


1 Answers

The first thing to establish is that interfaces were added to Delphi to support COM. So a lot of the design decisions were driven by a desire to make COM programming easier.

Interface references could perfectly well be manually managed. In fact, raw COM in C and C++ did originally involve manual reference count management with explicit calls to AddRef and Release. When consuming COM objects from C you still need to perform manual reference count management. For C++ these days you typically use a class like CComPtr to enable automatic reference count management.

When COM support was being added to Delphi, the main competitor to Delphi was VB. And in VB you've never had to do manual reference count management. Had the Delphi designers not implemented automatic reference count management, it would have been much harder to woo VB programmers to leave VB and start using Delphi. So, I speculate that this was a driver in the decisions the Delphi designers made. Even were that not the case, it is much easier to code against automatic reference counting than to program it manually. So even if my speculation is wrong, the decision that the Delphi designers took makes life a lot simpler.

So to come to your specific questions:

Why can't they be manually managed like a regular object?

They can be. You can implement _AddRef and _Release so that they do not control the lifetime of the object. Specifically, it is not compulsory for these methods to count references, nor for _Release to call Free.

Did the Delphi designers just decide to use reference counting since it was needed for COM?

Well, it is not needed for COM. As I said above, you can code against COM in C or C++ (or indeed other languages) without automatic reference counting.


Another question that you might have asked, is why Delphi interfaces have to derive from IInterface. This stems from their original purpose, which was to implement COM interfaces. In many ways, it would be nice if we could have interfaces that did not derive from IInterface. But it is what it is.

like image 135
David Heffernan Avatar answered Nov 15 '22 06:11

David Heffernan