Delphi memory management design strategies : Object or Interface?
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.
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.
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.