Setting array length without initializing/reallocating.

Sönke Ludwig sludwig at outerproduct.org
Sat Dec 12 13:30:51 UTC 2020


Am 12.12.2020 um 01:53 schrieb Jonathan Levi:
> Wow, there went several hours of debugging.
> 
> Increasing the length of a slice, by setting its length, will initialize 
> the new elements and reallocate if necessary.
> 
> I did not realize length was "smart", I guess I should have guessed.
> 
> Anyway, to work around this, and probably also be more clear, create a 
> new slice from the same pointer.
> 
> `array = array.ptr[0..newLength];`

One way around this is to call `array.assumeSafeAppend();` before 
setting the new length. In this case it will reuse the already allocated 
block as long as it is large enough and only reallocate if necessary.


More information about the Digitalmars-d mailing list