More on C++ stack arrays
Walter Bright
newshound2 at digitalmars.com
Sun Oct 20 11:42:05 PDT 2013
On 10/20/2013 10:46 AM, bearophile wrote:
> 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).
If your optimizing compiler is that good, it can optimize "new T[n]" to be on
the stack as well.
I'm not particularly enamored with the compiler inserting silent copying to the
heap - D programmers tend to not like such things.
> 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.
Rust is barely used at all, and constantly changes. I saw a Rust presentation
recently by one of its developers, and he said his own slides showing pointer
stuff were obsolete. I don't think there's enough experience with Rust to say it
teaches us how to do things.
> This over-allocates on the stack,
I use this technique frequently. Allocating a few extra bytes on the stack
generally costs nothing unless you're in a recursive function. Of course, if
you're in a recursive function, stack allocated dynamic arrays can have
unpredictable stack overflow issues.
> and sometimes needlessly allocates on the heap
> or in an arena. Dynamic stack arrays avoid those downsides.
The technique I showed is also generally faster than dynamic stack allocation.
More information about the Digitalmars-d
mailing list