【心得】關於刪除結構體動態數組指定項的正確方法

網絡上不少前輩提供的方法大可能是這樣寫的:數組

procedure DeleteArrItem(var arr: TArr; Index: Integer);
var
  Count: Cardinal;
begin
  Count := Length(arr);
  if (Count = 0) or (Index < 0) or (Index >= Count) then Exit;
  Move(arr[Index+1], arr[Index], (Count-Index)* SizeOf(arr[0]));
  SetLength(arr, Count - 1);
end;

這個方法刪除非結構體動態數組或者不帶string的結構體動態數組通常是沒有問題的。網絡

可是若是結構體中有string類型的數據,那用這個方法就會報內存泄漏。spa

解決的方法就是給結構體中string類型限定字符,好比string[10],這樣調用上面的方法刪除動態數組中的指定項就不會有問題了。code

相關文章
相關標籤/搜索