Why does the program crash when using const string arguments?

Dan*_*all 6 memory delphi string crash const

My program has following code:

function FooBar(const s: string): string;
var
  sa: AnsiString;
begin

  // ..........................

  sa := AnsiString(s);
  sa := AnsiString(StringReplace(string(sa), '*', '=', [rfReplaceAll]));
  sa := AnsiString(StringReplace(string(sa), ' ', '+', [rfReplaceAll]));
  result := string(sa);

  // ..........................

end;
Run Code Online (Sandbox Code Playgroud)

I noticed that the program did crash "somewhere" and FastMM4 said that I had written to a freed object. As soon as I have commented out "const", the program did work.

I have read the Delphi documentation about const arguments, but I can't figure out why the const argument crashes the program. I would love to understand it.

UPDATE: The program does only crash in Delphi 6 and only if optimization is ON. If the optimization is OFF, the program will work normally. Might it be a Delphi bug?

MBo*_*MBo 2

对于本例:

 sa := s;
Run Code Online (Sandbox Code Playgroud)

自动引用计数(ARC)起作用。这是惯用的方式,编译器知道如何处理这些字符串 - 如果 sa 发生变化,它会创建新的副本等等。

对于硬类型转换的情况(尽管类型相同)

sa := AnsiString(s);
Run Code Online (Sandbox Code Playgroud)

您告诉编译器您只想获取指向字符串的指针,并且您知道如何使用此字符串引用。编译器不会干扰和烦扰你,但你要对正确操作负责

PS 我无法用 Delphi XE5 重现问题 - 简单的赋值和类型转换都会导致 LStrLAsg(内部函数)使用 ARC 进行调用。(当然,编译器魔法可以稍微改变一下)