Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Container to store anonymous methods

I have a following definition.

type
  TOmniTaskDelegate = reference to procedure(const task: IOmniTask);

What type of container should I use (should be supported in D2009) to store a list of TOmniTaskDelegate instances? Currently I'm using array of TOmniTaskDelegate but I'm not really happy with that.

like image 830
gabr Avatar asked Apr 10 '26 04:04

gabr


2 Answers

I would use TList<TOmniTaskDelegate>. Since this is typesafe due to the use of generics, it will correctly handle the lifetime issues of its members.

like image 190
David Heffernan Avatar answered Apr 12 '26 15:04

David Heffernan


Edit: Delphi 2009 includes the generic TList<T>, I assume it's implemented using array of, just as the one in Delphi 2010. That makes the TList<T> the optimal choice! My original answer stays because it explains why array of is a great data structure and why not using it is a lot of trouble.


Your choice of array of Anonym looks very good to me because:

  • Anonymous methods are managed entities (implemented using interfaces). They need to be properly finalized.
  • The dynamic array is itself a managed type, making sure the anonymous method references are properly finalized.
  • Delphi 2010 generic containers are implemented using dynamic arrays, so they're up to the task. But make sure you don't grow your arrays one-by-one, grow in chunks.

If you use anything else for the implementation you'll need to take care of finalizing the references yourself. Examples:

  • If you use plain blocks of memory you'll need an destructor that deliberately sets each item to nil (ie: not ZeroMemory or FillChar) so the compiler gets a chance to generate finalization code.
  • Records are managed objects, and they could hold references to dynamic methods, but they can only hold a finite number of references, if you need more you'll need to implement a sort of linked list and then you'll need to carefully manage there life cycle.
  • Classes suffer all the deficiencies of records, and they add their own layer of overhead on top of that.
like image 38
Cosmin Prund Avatar answered Apr 12 '26 14:04

Cosmin Prund



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!