7

Regarding Delphi memory management, what are your design strategies ?

  • What are the use cases where you prefer to create and release Objects manually ?
  • What are the uses cases where Interfaces, InterfacedObjects, and their reference counting mechanism will be preferred ?

Do you have identified some traps or difficulties with reference counted objects ?

Thanks for sharing your experience here.

Bruce McGee
  • 15,076
  • 6
  • 55
  • 70
Pierre-Jean Coudert
  • 9,109
  • 10
  • 50
  • 59

2 Answers2

7

Whenever you share objects between threads it is better to use interfaces. A shared object doesn't necessarily have one identifiable owner, so letting the thread that gives up the last reference to the interface free the implementing object is a natural fit. See the OmniThreadLibrary for a good example of how to make use of interfaces both for design and for overcoming some of the complicated ownership issues in multi-threaded code.

mghie
  • 32,028
  • 6
  • 87
  • 129
1

You should always prefer interfaces unless it's not possible due to VCL restrictions. I suspect that, had interfaces been available in Delphi 1.0, the VCL would have turned out very differently.

One minor consideration is to watch out for reference cycles. If A holds an interface to B and B holds an interface to A, they will both live forever.

Marcelo Cantos
  • 181,030
  • 38
  • 327
  • 365
  • Could you detail those VCL restrictions please ? – Pierre-Jean Coudert Mar 31 '10 at 07:49
  • 3
    Simply that many of the VCL classes use different mechanisms for memory management, and you can't just slip an interface in between. The obvious case is TComponent's children, which are owned by the parent and destroyed by when it is destroyed. – Marcelo Cantos Mar 31 '10 at 07:55
  • 2
    VCL components can have all sorts of references to each other, implementing Components as interfaces would cause a circular reference nightmare. – The_Fox Mar 31 '10 at 11:40
  • @The_Fox I don't think that there is a fundamental difference between circular references for object instances or interfaces. Interfaces are even one of the recommended solutions to resolve circular unit interfaces. see http://stackoverflow.com/questions/2356318/delphi-enterprise-how-can-i-apply-the-visitor-pattern-without-circular-reference/2356690#2356690 – mjn Jul 05 '10 at 05:35
  • 2
    @mjustin: @The_Fox is talking about cyclic object references, which cause leaks when you use reference-counting, as interfaces do. – Marcelo Cantos Jul 05 '10 at 07:23