views:

298

answers:

2

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.

+1  A: 

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
Could you detail those VCL restrictions please ?
Pierre-Jean Coudert
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
VCL components can have all sorts of references to each other, implementing Components as interfaces would cause a circular reference nightmare.
The_Fox
@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
mjustin
@mjustin: @The_Fox is talking about cyclic object references, which cause leaks when you use reference-counting, as interfaces do.
Marcelo Cantos
+7  A: 

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