Implementing a List of Entries

The next question is this question : (note that this is not a duplicate, I ask for alternatives here).

Is there any way to do the following work:

type List <T> = record private FList : TList <T>; FGuard : IInterface, procedure CheckCreated; public procedure Add(const Value : T); end; procedure List <T>.CheckCreated; begin if (FGuard = nil) then begin FList := TList <T>.Create; FGuard := TGuard.Create (FList); // guard calls free on list in destructor end; end; procedure List <T>.Add (const Value : T); begin CheckCreated; FList.Add (Value); end; 

Ideally, I want to use it as follows:

 function ReturnHandles : List <THandle>; begin Result.Add (2); Result.Add (3); end; 

As explained in the answers to a related question, this does not work (which is really useless). He will not create a new list for each call.

Unfortunately, this does not work either:

 function ReturnHandles : List <THandle>; begin Initialize (Result); Result.Add (2); Result.Add (3); end; 

It removes security interfaces and all lists because Initialize simply rewrites the link to the interface without decreasing the link count.

Is there any way to make this work? Or would you suggest making this interface instead of recording and just living with a construction line?

 function ReturnHandles : List <THandle>; begin Result := List <T>.Create; Result.Add (2); Result.Add (3); end; 

Thank you for your help!

+4
source share
1 answer

This should work fine if I understand you correctly:

 function ReturnHandles : List <THandle>; begin Finalize(Result); Result.Add (2); Result.Add (3); end; 

Calling Finalize ensures that all managed types will be set to nil , which I believe are your intentions.

This question is very closely related to your previous question, and I think you could use the out parameters to simplify the code. The result of the function is implicitly the var parameter, but if you use the explicit out parameter, it will initialize the managed types as you wish.

 procedure InitializeHandles(out Handles : List <THandle>); begin Handles.Add (2); Handles.Add (3); end; 

Personally, since you are introducing the interface into the mix, I think that I would be inclined to go the full way and use the interfaces exclusively. Or use standard classes and accept the need to manage the try / finally lifecycle.

+2
source

Source: https://habr.com/ru/post/1386683/


All Articles