dynamic array initialized within a short function.

coxalan coxalan at web.de
Wed Oct 17 02:05:08 PDT 2007


Thanks for your answers!

Frits van Bommel Wrote:

> Daniel Keep wrote:
> > Actually, you could add an overload of func like so:
> > 
> > int func() {
> >     auto g = new int[10];
> >     scope(exit) delete g;
> >     return func(g);
> > }
> > 
> > Now both approaches work, and you can use whichever is most appropriate.
> 
> If you're going to delete it anyway, and the length is a compile-time 
> constant, you might as well pass a static array from the second function 
> to the first instead.
> 
> Another option:
> ---
> int func(int[] g = null) {
>      g.length = 10;
>      // original function code goes here
> }
> ---
> If a sufficiently-sized buffer is passed in, it's used. If not, a buffer 
> is allocated. The main benefit over the 2-function approach is that only 
> a single function is needed (so less clutter), but it does still 
> heap-allocate when a new buffer is needed (and it doesn't delete such 
> newly-allocated buffers).

Thanks for your answers!


More information about the Digitalmars-d-learn mailing list