procedure TForm1.FormCreate(Sender: TObject);
var
  A: array of Integer;
begin
  SetLength(A, 3);
  ShowMessage(IntToStr(A[0]));
end;
不定项选择题:
A. 此段代码会造成内存泄漏;
B. 在SetLength之后,A[0]、A[1]和A[2]总是0;
C. ShowMessage之后应当使用SetLength(A, 0)来释放内存;
D. 在SetLength之后,A[0]、A[1]和A[2]都是不确定的值。

解决方案 »

  1.   

    procedure       _SetLength(s: PShortString; newLength: Byte);
    begin
      Byte(s^[0]) := newLength;   // should also fill new space
    end;
    出自System.pas 3589行
      

  2.   

    S is a Delphi string or dynamic-array variable. NewLength is the new number of characters or elements in S. For a short-string variable, SetLength simply sets the length-indicator character (the character at S[0]) to the given value. In this case, NewLength must be a value between 0 and 255. For a long-string or dynamic-array variable, SetLength reallocates the string or array referenced by S to the given length. Existing characters in the string or elements in the array are preserved, but the content of newly allocated space is undefined. The one exception is when increasing the length of a dynamic array in which the elements are types that must be initialized (strings, Variants, Variant arrays, or records that contain such types). When S is a dynamic array of types that must be initialized, newly allocated space is set to 0 or nil. For dynamic arrays, SetLength may take more than one length parameter (up to the number of array dimensions). Each parameter specifies the number of elements along a particular dimension. Following a call to SetLength, S is guaranteed to reference a unique string or array—that is, a string or array with a reference count of one. If there is not enough memory available to reallocate the variable, SetLength raises an EOutOfMemory exception. 
      

  3.   

    说原因是吗:A. 此段代码会造成内存泄漏;
    B. 在SetLength之后,A[0]、A[1]和A[2]总是0;
    C. ShowMessage之后应当使用SetLength(A, 0)来释放内存;
    D. 在SetLength之后,A[0]、A[1]和A[2]都是不确定的值。首先对于A, C答案, 动态数组和字符串都是Managed的类型, 之前在你的关于局部变量那个帖子里我写过, 所以, 这里由SetLength申请的资源都会经过delphi隐式的加入的try Finally自动清除.对于B, D 答案, delphi的源码System里已经有答案了, 无需再细细的解释了
      

  4.   

    System单元的源码老多了!哪里才是答案呢?
      

  5.   

    从这段SetLength的帮助只能确定选D,谢谢。
      

  6.   


    看几个函数 system.pas_SetLength
    _LStrSetLength
    _UStrSetLength
    _WStrSetLength
    _DynArraySetLength
    DynArraySetLength
      

  7.   

    A. 不会内存泄露,因为编译器对动态数组采用引用计数管理技术,当脱离作用域范围后引用计数-1,这和string是一样的。
    B. undefined
    C. 根据自己的需要,赋值nil或setlength(0)都可。这样做是好的编程习惯。
    D. undefined
      

  8.   

    好吧,公布答案吧:
    选B。
    原因:
    SetLength -> _DynArraySetLength -> DynArraySetLength -> FillChar。补充说明:
    procedure TForm1.FormCreate(Sender: TObject);
    var
      a: array of Integer;
    begin
      SetLength(a, 3);
      a[0] := 1;
      a[1] := 2;
      a[2] := 3;
      SetLength(a, 5);
      ShowMessage(IntToStr(a[4]));//a[0], a[1]和a[2]依然分别是1,2和3,a[4]和a[5]都是0
      SetLength(a, 2);
      ShowMessage(IntToStr(a[0]));//a[0]和a[1]依然分别是1和2
    end;