让TList类型安全

http://tech.ddvip.com   2006年03月30日    社区交流

本文详细介绍让TList类型安全

  在VCL中包含有一个TList类,相信很多朋友都使用过,它可以方便的维护对象指针,所以很多朋友都喜欢用它

  来实现控件数组。不幸的是,这个TList类有一些问题,其中最重要就是缺乏类型安全的支持。

  这篇文章介绍如何从TList派生一个新类来实现类型安全,并且能自动删除对象指针的方法。

  TList的问题所在

  对于TList的方便性这里就不多说,我们来看一下,它到底存在什么问题,在Classes.hpp文件中,我们可以看到函数的原型是这样申明的:

  int __fastcall Add(void * Item);

  编译器可以把任何类型的指针转换为void*类型,这样add函数就可以接收任何类型的对象指针,这样问题就来了,如果你仅维护一种类型的指针也许还看不到问题的潜在性,下面我们以一个例子来说明它的问题所在。假设你想维护一个TButton指针,TList当然可以完成这样的工作但是他不会做任何类型检查确保你用add函数添加的一定是TButton*指针。

  TList *ButtonList = new TList;    // 创建一个button list
ButtonList->Add(Button1);       // 添加对象指针
ButtonList->Add(Button2);       //
ButtonList->Add( new TButton(this)); // OK so far
ButtonList->Add(Application);     // Application不是button
ButtonList->Add(Form1);        // Form1也不是
ButtonList->Add((void *)534);
ButtonList->Add(Screen);

  上面的代码可以通过编译运行,因为TList可以接收任何类型的指针。

  当你试图引用指针的时候,真正的问题就来了:

  TList *ButtonList = new TList;
ButtonList->Add(Button1);
ButtonList->Add(Button2);
ButtonList->Add(Application);
TButton *button = reinterpret_cast<TButton *>(ButtonList->Items[2]);
button->Caption = "I hope it's really a button";
delete ButtonList;

责编:豆豆技术应用

正在加载评论...