Pointer(s)^ versus s[1]

前端 未结 7 989
南旧
南旧 2021-02-12 14:56

In a function that reads data (data meaning exclusively strings) from disk, which should I prefer? Which is better?

A) DiskStream.Read(Pointer(s         


        
7条回答
  •  甜味超标
    2021-02-12 15:01

    If there is ever any chance that your function will be called with a Count of 0, then A) will work with Pointer(s)^ simply evaluating to nil while B) will crash with a range check exception.

    If you want to use B) and still handle counts of 0 gracefully, you should use:

    function TMyStream.ReadChars(out s: AnsiString; const Count: Integer): Boolean; 
    begin
     SetLength(s, Count);
     Result := (Count = 0)  or (Read(s[1], Count) = Count);
    end;
    

提交回复
热议问题