is there a cleaner way to new a static sized array?

Steven Schveighoffer schveiguy at yahoo.com
Thu Feb 25 05:23:31 PST 2010


On Tue, 23 Feb 2010 23:16:35 -0500, BCS <none at anon.com> wrote:

> I need a function that works like the following:
>
>> T* New(T)() { return new T; }
>
> But that also works with static arrays:
>
>> auto i = New!(int)();
>> auto a = New!(int[27])();
>
> The cleanest solution I can think of is:
>
>> T* New(T)() { return (new T[1]).ptr; }
>
> but that seems ugly. Any ideas?

Want to hear something funny?  In developing the array append patch to fix  
stomping, I worried about how memory would be allocated for something like  
this:

int *i = new int;

Simply because I was worried someone would do:

int[] x = i[0..1];
x ~= 4;

If this didn't do the right thing, my array stomping patch might make this  
do the wrong thing.

But as it turns out, the d compiler basically rewrites the line

int * i = new int;

to

int * i = (new int[1]).ptr;

Yep, that's exactly what you did :)  So basically your solution *is* the  
solution to use, because it's what the compiler would do if the syntax was  
allowed.

Some people have proposed recently on the digitalmars.D newsgroup that  
dynamic array allocation with the dimension in the brackets should  
actually allocate a statically-sized array on the heap.  The only allowed  
form for dynamic arrays would be:

int[] x = new int[](1);

Which is currently valid, but would be the only way to allocate dynamic  
arrays.

Although it looks uglier and does not conform to other languages (such as  
java or C#), it allows you to easily allocate a statically-sized array.  I  
hope this change goes through.

Note that you can special case your "New" template for objects using  
static if or using template constraints (if you are on D2)

-Steve


More information about the Digitalmars-d-learn mailing list