Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 310
Pierre-Jean Coudert Avatar asked Mar 31 '10 07:03

Pierre-Jean Coudert


2 Answers

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.

like image 85
mghie Avatar answered Sep 23 '22 07:09

mghie


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.

like image 41
Marcelo Cantos Avatar answered Sep 21 '22 07:09

Marcelo Cantos