如何确定一个threadvar字符串以防止泄漏? [英] How to finalise a threadvar string to prevent a leak?

查看:225
本文介绍了如何确定一个threadvar字符串以防止泄漏?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这不是一个主要的漏洞,但是我认为更好的是整理,但是我发现我的Delphi XE代码可以泄漏字符串。这是因为它被定义为一个线程,因为它需要,但是当线程终止时,显然不能整理这样的变量。

This is not a major leak, but more of a would be nice to tidy I think, but I have found that my Delphi XE code can leak a String. This is because it is defined as a threadvar as it needs to be, but when the thread terminates, it is apparently not tidying up such variables.

有没有办法在线程终止时手动整理字符串?我只是给它分配一个空字符串,或者将其设置为nil或某些东西?

Is there a way for me to manually tidy a string on termination of the thread? Do I just assign an empty string to it, or set it to nil or something?

推荐答案

为其分配一个空字符串,将其设置为nil或调用 Finalize()。他们都是等同的,他们将释放存储空间,从而消除您的内存泄漏。

Assign an empty string to it, set it to nil or call Finalize() on it. They are all equivalent and they will deallocate the storage thus removing your memory leak.

为了回应Marco的评论,一个href =http://docwiki.embarcadero.com/RADStudio/en/Variables#Thread-local_Variables =nofollow>文档是明确的:

In response to Marco's comment, the documentation is explicit on this:


通常由编译器管理的
的动态变量(长字符串,
宽字符串,动态数组,
变体和接口)可以是
用threadvar声明,但
编译器不会自动释放
每个执行线程由
创建的堆分配内存。如果您在线程变量
中使用
这些数据类型,则您有责任在线程终止之前从
线程中处理
的内存。
例如:

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:

threadvar
  S: AnsiString;

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


相当奇怪的是,文档包含最后一行的明确错误应该是 S:= nil;

Rather bizarrely the documentation contains a clear error in the final line which should read S := nil;

当然很容易看到对于自己,线程局部变量不会自动处理:

It is of course easy to see for yourself that thread local variables are not disposed automatically:

program LeakMe;

{$APPTYPE CONSOLE}

threadvar
  s: string;

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

这篇关于如何确定一个threadvar字符串以防止泄漏?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆