我正在使用Delphi 2009,并使用以下代码段得到一些奇怪的错误:
var
Str : AnsiString;
CharPtr : PAnsiChar;
...
CharPtr := PAnsiChar (Str);
ExecuteInBackgroundThread (
procedure
begin
DoSomething (CharPtr);
end);
我猜想,当超出范围时,在某些计时条件下,字符串会被破坏,DoSomething将产生最奇怪的结果。所以第一个问题是:我说的对吗?
第二个问题是:如何避免被破坏的琴弦?这样做的正确方法是什么?
提前致谢。
最佳答案
So the first question is: am I right?
很有可能,是的。 Delphi的AnsiString被引用计数。当
Str
超出范围时,引用计数将减少。如果引用计数达到零,则可以重新使用它所占用的内存。Second question is: How can I circumvent the string being destructed? What's the proper way to to this?
通过不使用指针,如下所示:
var
Str : AnsiString;
...
ExecuteInBackgroundThread (
procedure
begin
DoSomething (Str);
end);
关于multithreading - 字符串过早销毁以及如何避免呢?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1524776/