More on C++ stack arrays

bearophile bearophileHUGS at lycos.com
Sun Oct 20 10:46:12 PDT 2013


Walter Bright:

> Just use:
>
>     auto a = new T[n];

Sometimes I don't want to do that.


> Stack allocated arrays are far more trouble than they're worth.

I don't believe that.


> But what about efficiency? Here's what I often do something 
> along the lines of:
>
>     T[10] tmp;
>     T[] a;
>     if (n <= 10)
> 	a = tmp[0..n];
>     else
> 	a = new T[n];
>     scope (exit) if (a != tmp) delete a;
>
> The size of the static array is selected so the dynamic 
> allocation is almost never necessary.

That's 7 lines of bug-prone code that uses a deprecated 
functionality and sometimes over-allocates on the stack. And I 
think you have to compare just the .ptr of those arrays at the 
end. And if you return one of such arrays you will produce 
nothing good. And what if you need 2D arrays? The code becomes 
even more complex. (You can of course create a matrix struct for 
that).

Dynamically sized stack allocated arrays are meant to solve all 
those problems: to offer a nice, compact, clean, easy to remember 
and safe syntax. To be usable for 2D arrays too; and when you 
pass or return one of them the data is copied by the compiler on 
the heap (sometimes this doesn't happen if the optimizing 
compiler allocates the array in the stack frame of the caller, as 
sometimes done for structs).

D dynamic array usage should decrease and D should encourage much 
more the usage of small stack-allocated arrays. This is what 
languages as Ada and Rust teach us. Heap allocation of arrays 
should be much less common, almost a special case.

----------------

Andrei Alexandrescu:

> Fallback allocators will make it easy to define an allocator on 
> top of a
fixed array,

This over-allocates on the stack, and sometimes needlessly 
allocates on the heap or in an arena. Dynamic stack arrays avoid 
those downsides.

Bye,
bearophile


More information about the Digitalmars-d mailing list