如果操作一个 record 指针中的字符串变量,会不会丢失 string 的内 结果是:使用 New() 分配的内存,会自动初始化 record 的内容,并且在 Dispose 时自动 代码如下: type {;$DEFINE NEW} procedure TForm1.Button1Click(Sender: TObject); =================================================== GetMem 只负责分配空间,不会负责清空刚分配的空间,如果需要分配来就 =================================================== 哦,我上面犯错误了,以为 S = 0 时也会出错,所以没有 FillChar,其实不会。 这样就可以正确测出结果了: type {;$DEFINE NEW} procedure TForm1.Button1Click(Sender: TObject); =================================================== 是的,FreeMem 不会释放其中的生存期自动管理的内容,因为在 FreeMem =================================================== 呵呵,不用估计,帮助中明确地说明了。 In Delphi code, FreeMem destroys the variable referenced by P and returns its memory to the heap. If P does not point to memory in the heap, a runtime error occurs. If P points to a structure that includes long strings, variants, dynamic arrays, or interfaces, call Finalize before calling Freemem. =================================================== In Delphi code, FreeMem destroys the variable referenced by P and returns its memory to the heap. If P does not point to memory in the heap, a runtime error occurs. If P points to a structure that includes long strings, variants, dynamic arrays, or interfaces, call Finalize before calling Freemem. 这段英文我翻译一下。 “在DELPHI代码中,FreeMem根据变量所引用的指针释放内存,并将内存归还给堆。如果指针不是指向堆中的内存地址,将发生一个运行时错误。如果指针所指向的是一个数据结构,且其中包含有长字符串、Variants、动态数组、或接口,则在使用用FreeMem之前须调用Finalize ” 翻译完了。肯定有不准确的地方。 =================================================== “容易使用”通常只能是一个相对的概念,在这里,我们讨论指向结构体的指针,在这种情况下,New/Dispose 通常是易用的。但是它们是有局限的,就是那个指针指向的空间的大小必须能够在编译期间确定,它们才知道需要分配多大的空间。对于指向结构体的指针,这个值就是结构体的大小,这当然是确定的,所以能够使用它们,并且能够带来便利。 还有没有必要使用GetMem、FreeMem,在什么情况下使用它们? 当然有了,如前面提到的,相对来说,New/Dispose 操作更为高层一些,我们通常用它们来操作指向结构体的指针,即是说指针指向的内容是编译期间就已知的数据结构。而当我们需要更加低级的去操作一些内存空间的时候,比如你要自己处理字符串的时候,你的指针指向的就是只有你自己才知道或者说是你自己去进行理解的内存空间,没有编译期间的明确的数据结构与之对应。这个时候,就要用到 GetMem/FreeMem 了。 |