More on C++ stack arrays

Jonathan M Davis jmdavisProg at gmx.com
Sun Oct 20 17:59:14 PDT 2013


On Sunday, October 20, 2013 09:33:36 Walter Bright wrote:
> On 10/20/2013 7:25 AM, bearophile wrote:
> > More discussions about variable-sized stack-allocated arrays in C++, it
> > seems there is no yet a consensus:
> > 
> > http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2013/n3810.pdf
> > 
> > I'd like variable-sized stack-allocated arrays in D.
> 
> They're far more trouble than they're worth.
> 
> Just use:
> 
>      auto a = new T[n];
> 
> Stack allocated arrays are far more trouble than they're worth. 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.

If that paradigm is frequent enough, it might be worth wrapping it in a 
struct. Then, you'd probably get something like

StaticArray!(int, 10) tmp(n);
int[] a = tmp[];

which used T[10] if n was 10 or less and allocated T[] otherwise. The 
destructor could then deal with freeing the memory.

- Jonathan M Davis


More information about the Digitalmars-d mailing list