Stack-allocated arrays

KennyTM~ kennytm at gmail.com
Wed Nov 12 03:26:01 PST 2008


Janderson wrote:
> Dave wrote:
>>> I'd love for "scope foo = new T[len];" to do for arrays what "scope 
>>> bar = new Class;" does for classes. And indeed, if it's too big the 
>>> compiler
>>
>> I'm surprised it doesn't and see that as a bit inconsistent, with the 
>> only serious argument against it being that 'scope' couldn't be used 
>> for large dynamic arrays.
>>
>> But then again:
>>
>> class C
>> {
>>   int[264_000] a;
>> }
>>
>> void foo()
>> {
>>    scope C c = new C;
>>    ...
>> }
>>
>> could also overflow the stack. In either case the work-around would be 
>> the same (increase the stack size or not use 'scope').
>>
> 
> As a work around, I imagine it would be possible to write a template 
> that used the above syntax with a static if that would change depending 
> on the size:  Something like this (untested):
> 
> 
> class FastArray(T, int size)
>     if (size < 1000)
> {
>     T[size] a;
>     ... Overload operators
> }
> 
> class FastArray(T, int size)
>     if (size >= 1000)
> {
>     T a[] = new T[size];
>     ... Overload operators
> }
> 
> 
> //Use
> 
> void foo()
> {
>     scope FastArray array = new FastArray!(int, 10); //Stack
>     scope FastArray array = new FastArray!(int, 10000); //Heap
> }
> 
> Of course you never know where you are in the stack, so nesting these to 
> much would be bad.

But this won't work if size is runtime-determined.



More information about the Digitalmars-d mailing list