Do TEnumerators need to be managed from shared containers?

If I call the GetEnumerator method of a Generics.Collections object, do I need to explicitly free the enumerator when I am done with it?

+4
source share
1 answer

Yes, you need to free the counter. Whoever calls GetEnumerator gets what it returns.

When it is a for/in loop, the compiler writes the code and ensures that the enumerator object is deleted. When you call this, your job is to recycle the counter.

This is actually a very simple question to answer. Just create a program that calls GetEnumerator and cannot Free it. Use the memory manager tools to check if an object has leaked.

 uses System.Generics.Collections; begin ReportMemoryLeaksOnShutdown := True; with TList<Integer>.Create do begin GetEnumerator; Free; end; end. 

And this will result in the following leak message:

An unexpected memory leak has occurred. Unexpected small block leaks are:

  • 13 - 20 bytes: TList.TEnumerator x 1
+8
source

All Articles