dynamic array initialized within a short function.

Frits van Bommel fvbommel at REMwOVExCAPSs.nl
Sun Oct 14 14:00:04 PDT 2007


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).


More information about the Digitalmars-d-learn mailing list