开发者

What happens when increasing the size of a dynamic array?

I'd like to understand what happens when the si开发者_JS百科ze of a dynamic array is increased.

My understanding so far:

  • Existing array elements will remain unchanged.
  • New array elements are initialised to 0
  • All array elements are contiguous in memory.

When the array size is increased, will the extra memory be tacked onto the existing memory block, or will the existing elements be copied to a entirely new memory block?

Does changing the size of a dynamic array have consequences for pointers referencing existing array elements?

Thanks,

[edit] Incorrect assumption struck out. (New array elements are initialised to 0)


  • Existing array elements will remain unchanged: yes
  • New array elements are initialized to 0: yes (see update) no, unless it is an array of compiler managed types such as string, an other array or a variant
  • All array elements are contiguous in memory: yes

When the array size is increased, the array will be copied. From the doc: ...memory for a dynamic array is reallocated when you assign a value to the array or pass it to the SetLength procedure.

So yes, increasing the size of a dynamic array does have consequences for pointers referencing existing array elements.

If you want to keep references to existing elements, use their index in the array (0-based).

Update

Comments by Rob and David prompted me to check the initialization of dynamic arrays in Delphi5 (as I have that readily available anyway). First using some code to create various types of dynamic arrays and inspecting them in the debugger. They were all properly initialized, but that could still have been a result prior initialization of the memory location where they were allocated. So checked the RTL. It turns out D5 already has the FillChar statement in the DynArraySetLength method that Rob pointed to:

  // Set the new memory to all zero bits
  FillChar((PChar(p) + elSize * oldLength)^, elSize * (newLength - oldLength), 0);


In practice Embarcadero will always zero initialise new elements simply because to do otherwise would break so much code.

In fact it's a shame that they don't officially guarantee the zero allocation because it is so useful. The point is that often at the call site when writing SetLength you don't know whether you are growing or shrinking the array. But the implementation of SetLength does know – clearly it has to. So it really makes sense to have a well-defined action on any new elements.

What's more, if they want people to be able to switch easily between managed and native worlds then zero allocation is desirable since that's what fits with the managed code.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜