Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delphi code migration issues

Tags:

delphi

I´m facing a problem between Delphi 2010 and Delphi Berlin (last update) during my code migration.... I made a simple code to demonstrante an strange behaviour...

I have an application that use TList (the former one) and TList (from Generics.Collections) I know that this piece of code (below) doesn´t make any sense for you, but it´s for demonstration purposes

unit Unit1;
interface
uses
  Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
  Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls;
type
  TTest = class
    Name: string;
    constructor Create(Nome: string);
  end;
  TForm1 = class(TForm)
    btn1: TButton;
    procedure btn1Click(Sender: TObject);
    procedure FormCreate(Sender: TObject);
  private
    FList: TList;
  end;
var
  Form1: TForm1;
implementation
uses
  System.Generics.Collections;
{$R *.dfm}

procedure TForm1.btn1Click(Sender: TObject);
var
  tmpList: TList<TTest>;
begin
  tmpList := TList<TTest>.Create;
  tmpList.Add(TTest.Create('A'));
  tmpList.Add(TTest.Create('B'));
  tmpList.Add(TTest.Create('C'));
  tmpList.Add(TTest.Create('D'));
  tmpList.Add(TTest.Create('E'));
  FList := TList(tmpList);
  ShowMessage(TTest(FList[0]).Name);
end;

procedure TForm1.FormCreate(Sender: TObject);
begin
  FList := TList.Create;
end;

constructor TTest.Create(Nome: string);
begin
  Name := Nome;
end;
end.

At Delphi 2010 the ShowMessage shows 'A' character, but on the Delphi Berlin it raises an Acess Violation

Both applications with Optimization set to False

like image 321
Tiago Avatar asked Jul 19 '17 18:07

Tiago


1 Answers

FList := TList(tmpList);

This is the problem. The cast is simply wrong, because tmpList is not a TList.

Your code only compiles because of the cast, but the cast does not change the fact that the object on the right hand side is not of the type being casted to. All the cast does is stop the compiler from complaining and saving you from yourself. Your cast is a lie to the compiler, and the runtime error is the consequence.

This code might have worked in older versions, but only by chance. Your luck has changed.

Hard to know what to suggest for a fix. As you say, the code makes little sense. Every time you press the button, you leak a list. I'd suggest that you remove all the casts, stop using the non-Generic TList and use only Generic lists.

like image 75
David Heffernan Avatar answered Nov 15 '22 05:11

David Heffernan