参考计数

计算字符串的引用是线程安全的。锁和异常处理程序用于保护进程。请考虑以下代码,其中注释指示编译器在编译时插入代码以管理引用计数的位置:

procedure PassWithNoModifier(S: string);
// prologue: Increase reference count of S (if non-negative),
//           and enter a try-finally block
begin
  // Create a new string to hold the contents of S and 'X'. Assign the new string to S,
  // thereby reducing the reference count of the string S originally pointed to and
  // brining the reference count of the new string to 1.
  // The string that S originally referred to is not modified.
  S := S + 'X';
end;
// epilogue: Enter the `finally` section and decrease the reference count of S, which is
//           now the new string. That count will be zero, so the new string will be freed.
    
procedure PassWithConst(const S: string);
var
  TempStr: string;
// prologue: Clear TempStr and enter a try-finally block. No modification of the reference
//           count of string referred to by S.
begin
  // Compile-time error: S is const.
  S := S + 'X';
  // Create a new string to hold the contents of S and 'X'. TempStr gets a reference count
  // of 1, and reference count of S remains unchanged.
  TempStr := S + 'X';
end;
// epilogue: Enter the `finally` section and decrease the reference count of TempStr,
//           freeing TempStr because its reference count will be zero.

如上所示,引入临时本地字符串以保存对参数的修改涉及与直接对该参数进行修改相同的开销。声明字符串 const 仅在字符串参数真正为只读时避免引用计数。但是,为了避免在函数外部泄漏实现细节,建议始终在字符串参数上使用 constvarout 之一。