关于delphi:如何最终确定threadvar字符串以防止泄漏?

How to finalise a threadvar string to prevent a leak?

这不是主要的泄漏,但是我认为可以将其整理得整整一点,但是我发现我的Delphi XE代码可以泄漏String。这是因为根据需要将其定义为threadvar,但是当线程终止时,显然并没有整理这些变量。

我是否可以在线程终止时手动整理字符串?我只是给它分配一个空字符串,还是将其设置为nil之类的?


为其分配一个空字符串,将其设置为nil或在其上调用Finalize()。它们都是等效的,它们将重新分配存储空间,从而消除了内存泄漏。

为回应Marco的评论,此文档的内容很明确:

Dynamic variables that are ordinarily
managed by the compiler (long strings,
wide strings, dynamic arrays,
variants, and interfaces) can be
declared with threadvar, but the
compiler does not automatically free
the heap-allocated memory created by
each thread of execution. If you use
these data types in thread variables,
it is your responsibility to dispose
of their memory from within the
thread, before the thread terminates.
For example:

1
2
3
4
5
6
threadvar
  S: AnsiString;

S := 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
  ...
S := ;  // free the memory used by S

奇怪的是,文档的最后一行包含明显错误,应显示为S := nil;

当然,您很容易发现线程局部变量不会自动处理:

1
2
3
4
5
6
7
8
9
10
11
program LeakMe;

{$APPTYPE CONSOLE}

threadvar
  s: string;

begin
  ReportMemoryLeaksOnShutdown := True;
  s := 'Leak me';
end.


其他一些小解决方案-您可以在此处使用ShortString而不是String(或任何其他类型的固定长度数组),然后内存泄漏消失