參考計數

計算字串的引用是執行緒安全的。鎖和異常處理程式用於保護程序。請考慮以下程式碼,其中註釋指示編譯器在編譯時插入程式碼以管理引用計數的位置:

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 之一。