Delphi TPair exception

I have this surge for testing TPair. You can copy + paste the new Delphi XE console application. I marked a line with an exception:

Project Project1.exe throws an exception to the EAccessViolation class with the message "Access violation at address 0045042D in the module Project1.exe. Read address A9032D0C.

Any idea?

Thanks.

program Project1; {$APPTYPE CONSOLE} uses SysUtils, Generics.Defaults, Generics.Collections; type TProduct = class private FName: string; procedure SetName(const Value: string); published public property Name: string read FName write SetName; end; type TListOfProducts = TObjectDictionary<TProduct, Integer>; { TProduct } procedure TProduct.SetName(const Value: string); begin FName := Value; end; var MyDict: TListOfProducts; MyProduct1: TProduct; MyProduct2: TProduct; MyProduct3: TProduct; APair: TPair<TProduct, Integer>; aKey: string; begin try MyDict := TListOfProducts.Create([doOwnsKeys]); MyProduct1 := TProduct.Create; MyProduct1.Name := 'P1'; MyProduct2 := TProduct.Create; MyProduct2.Name := 'P2'; MyProduct3 := TProduct.Create; MyProduct3.Name := 'P3'; MyDict.Add(MyProduct1, 1); MyDict.Add(MyProduct2, 2); MyDict.Add(MyProduct3, 3); APair := MyDict.ExtractPair(MyProduct1); Writeln(APair.Key.Name); // <--- Error is Here. Writeln(IntToStr(APair.Value)); Readln(aKey); except on E: Exception do Writeln(E.ClassName, ': ', E.Message); end; end. 
+5
source share
1 answer

This is a Delphi error. TDictionary<TKey,TValue>.ExtractPair does not assign Result .

RRUZ detected an error in QC .

The code reads:

 function TDictionary<TKey,TValue>.ExtractPair(const Key: TKey): TPair<TKey,TValue>; var hc, index: Integer; begin hc := Hash(Key); index := GetBucketIndex(Key, hc); if index < 0 then Exit(TPair<TKey,TValue>.Create(Key, Default(TValue))); DoRemove(Key, hc, cnExtracted); end; 

Result must be assigned when calling DoRemove .

It is very difficult to get around this error. ExtractPair is the only way to get an element from the dictionary without destroying the key, and therefore you must call it. But since it will not return the extracted element, you need to read the element first, remember the value, and then call ExtractPair .

+11
source

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


All Articles