Unitialized allocation

Koroskin Denis 2korden at gmail.com
Fri Jun 27 11:20:34 PDT 2008


On Fri, 27 Jun 2008 21:22:50 +0400, Jarrett Billingsley  
<kb3ctd2 at yahoo.com> wrote:

> "Koroskin Denis" <2korden at gmail.com> wrote in message
> news:op.udevrrqpenyajd at proton.creatstudio.intranet...
>>
>> This surely should be available at a language level.
>
> It would be nice, but I'm not sure how it'd fit into the syntax.
>
> new(void) char[512] ?
> new void char[512] ?
>
>

Think different!

Let's suppose we have the following:
T[] t = new T[512]; // initialized to T.init

Now how do I resize `t` so that it would now contain 1024 elements (and  
first 512 of them remain the same)?
t.length = 1024;	// nope. initializes the rest of data

There is a solution of my preference - introduce a resize method (yes,  
that's a proposal):

import std.gc;

T[] resize(T)(ref T[] array, uint newLength, bool doInit = true) {
     if (doInit) {
         array.length = newLength;
         return array;
     }

     return array.resizeUninited(newLength);
}

T[] resizeUninited(T)(ref T[] array, uint newLength) {
     return array = cast(T[])realloc(array.ptr, newLength * T.sizeof);
}

t.resize(1024, true);	// initializes the data
t.resize(1024);		// a shortcut, same as above

t.resize(1024, false);	// here it is - that's what we need!
t.resizeUninited(1024);	// a shortcut

So, back to the original question: "[how to] allocate unitialized data on  
the heap ?"

My solution is to break it into two steps:
T[] t;
t.resize(1024, false); // or t.resizeUninited(1024, false);

What do you think?


More information about the Digitalmars-d-learn mailing list