静态array的内存分配策略究竟是什么?(200分)

A

afay

Unregistered / Unconfirmed
GUEST, unregistred user!
在Delphi自带的帮助上看到静态array的内存是固定的,也就是说一旦申明了就会划一块内存留起备用。
但是我在看TStringList的源代码时却看到它用静态数组,而且上限还很大,源代码在classes.pas文件的540行,内容如下:
PStringItemList = ^TStringItemList;
TStringItemList = array[0..MaxListSize] of TStringItem;
TStringList = class(TStrings)
private
FList: PStringItemList;
......

上面在申明变量FList时使用的是指针,但该指针指向的是静态数组啊?是不是用指针就不会分配内存了??

 
没错,指针不会分配内存,所以我们用指针的时候都要自己管理内存
 
FList: PStringItemList;
仅仅是一个指针, 并没有静态的 array
用到的时候, 动态分配内存, 动态增大不够用的时候, 重新分一个较大的, 这是基本的技巧
 
PStringItemList = ^TStringItemList;//只是指针,指向自己动态分配内存,类型只是说明了存储的规则
TStringItemList = array[0..MaxListSize] of TStringItem;//MaxListSize我记得=MaxInt div 4 -1 (2^32/4-1=2^28-1)也就是最多指向1G个Item

TStringList = class(TStrings)
private
FList: PStringItemList;
FCount: Integer;
procedure SetCount(const Value: Integer);
public
property Count: Integer read FCount write SetCount;
property Item[Index: Integer]: string read GetItem write SetItem;

//其实实际根本就不存在数组,仅仅是指示如何操作数据.主要是为了方便.这是基本技巧
procedure TStringList.SetCount(const Value: Integer);
var
NewPtr: PStringItemList;
aInt: Integer;
begin
..
//(容量大小不做检查,统一从新分配,不做优化,拷贝采用循环,以示原理,不用CopyMemory,不进行异常处理,只考虑容量增加,未作删除操作)
if Value<=FCount then raise Exception.Create('只考虑容量增加,未作删除操作');
NewPtr:= GetMemory(Value*SizeOf(TStringItemList));
ZeroMemory(NewPtr, Value*SizeOf(TStringItemList));
for aInt:= 0 to Value-1 do
NewPtr[aInt]:= FList[aInt];
FreeMemory(FList);
FList:= NewPtr;
FCount:= Value;
end


 
由于对delphi不太熟,希望各位能推荐一下对delphi基础讲得比较深入的书。谢谢
 

Similar threads

回复
0
查看
519
不得闲
S
回复
0
查看
950
SUNSTONE的Delphi笔记
S
S
回复
0
查看
772
SUNSTONE的Delphi笔记
S
S
回复
0
查看
3K
SUNSTONE的Delphi笔记
S
顶部