RAD Studio VCL Reference
ContentsIndex
PreviousUpNext
System.UniqueString Function

Ensures that a given string has a reference count of one.

Pascal
procedure UniqueString(var str: AnsiString); overload;
procedure UniqueString(var str: WideString); overload;
procedure UniqueString(var str: UnicodeString); overload;
C++
UniqueString(AnsiString str);
UniqueString(BSTR str);
UniqueString(UnicodeString str);

UniqueString forces the reference count on a string to one, copying the string in memory if necessary. For normal string handling, there is no need to call UniqueString. UniqueString is used only in cases where an application modifies the contents of a string after:

  • casting the string to a PAnsiChar or PWideChar in Delphi.
  • using the c_str(), t_str() or data() methods of UnicodeString or AnsiString or the c_bstr() method of WideString in C++. (It's better to use data() than c_str() because c_str() returns an empty string for a NULL UnicodeString or AnsiString.)

 

Delphi Examples: 

{
The following code demostrates the use of Ptr function. The example
makes use of Ptr to simulate pointer arithmetics.
}
function FastUpperCase(const S: String): String;
var
  C: ^Char;
  I: Integer;
begin
  { Get the text in the edit box }
  Result := S;

  { Ensure the string reference stored in Result is unique,
    otherwise we may change the original string also.
    No copy-on-write is done if we're accesing the character
    directly.
  }
  UniqueString(Result);

  { Find the address of the first char in the string }
  C := Addr(Result[1]);

  for I := 0 to Length(Result) - 1 do
  begin
    { Up-case the character }
    C^ := UpCase(C^);

    { Move to the next character }
    C := Ptr(Integer(C) + SizeOf(Char));
  end;
end;


procedure TForm1.Button1Click(Sender: TObject);
begin
  { Uppercase the string in the edit box }
  Edit1.Text := FastUpperCase(Edit1.Text);
end;

 

Copyright(C) 2009 Embarcadero Technologies, Inc. All Rights Reserved.
What do you think about this topic? Send feedback!