new T[size] vs .reserve

monarch_dodra monarchdodra at gmail.com
Sun Feb 3 00:04:03 PST 2013


On Sunday, 3 February 2013 at 00:34:48 UTC, Namespace wrote:
> On Saturday, 2 February 2013 at 22:39:58 UTC, monarch_dodra 
> wrote:
>> On Saturday, 2 February 2013 at 22:15:56 UTC, Namespace wrote:
>>> My real question was: will we ever have fixed size arrays at 
>>> runtime?
>>
>> I see no reason why we couldn't, the only problem is a syntax 
>> one. If you beat the syntax (by wrapping it in a struct) then 
>> you can do it no problem:
>>
>> //----
>> T[N]* makeFixed(size_t N, T)()
>> {
>>    static struct Fixed
>>    {
>>        T[N] a;
>>    }
>>    auto p = new Fixed();
>>    return &((*p).a);
>> }
>>
>> void main()
>> {
>>   int[4]* p4 = makeFixed!(4, int)();
>> }
>> //----
>>
>> And there, a dynamically allocated fixed size array. I know 
>> it's not pretty, but it proves the point.
>
> Sure and as I said: something like that I'm using currently. It 
> is very ugly and because of that I asked for a built in 
> solution, like new ubyte[size].
> [SNIP]
> But as far as I can see all your are fine with the wrapped 
> struct solution.

I never said I was happy with this solution! The problem is that 
the old "new int[4]" syntax is already taken and means "allocate 
a dynamic array of size 4".

> C have also runtime fixed size arrays.

C has "variable length arrays". That's not exactly the same same 
thing as allocating a fixed size array at runtime (apologies if I 
was confused by your requirement).

If you want variable length arrays, you should be able to do it 
with the low level "alloca".


More information about the Digitalmars-d-learn mailing list