Don't use arrays as stacks

Steven Schveighoffer schveiguy at yahoo.com
Mon Sep 26 05:57:05 PDT 2011


On Sun, 25 Sep 2011 02:37:25 -0400, Nick Sabalausky <a at a.a> wrote:

> If anyone cares, I've put up a little thing about why it's best not to  
> use
> D's arrays as stacks. This is drawn from a direct experience a few months
> ago. Figured if I fell into that trap then others might too, so this  
> could
> be helpful for some people. There's a no-login-needed comments section
> already there.
>
> https://www.semitwist.com/articles/article/view/don-t-use-arrays-as-stacks
>
>

Nice article!

> For more information about D's arrays and slicing, see Steven  
> Schveighoffer's award-winning article, D Slices.

:D

> [1] Why is the capacity set to zero instead of the actual length of  
> four? I'm not certain, but my guess is that zeroing the value is  
> slightly faster than copying the length. Either that, or perhaps it has  
> to do with the fact that the slice doesn't actually "own" the data.

It was an arbitrary decision, but actually serves as an important  
differentiator.  0 simply means "any append to this array will  
reallocate".  capacity == length would mean the same thing, but has the  
distinction of knowing that the length is the actual block length.  This  
might not seem like much, but you may want to know this difference, for  
example, if you wanted to call assumeSafeAppend.  The stack example is a  
good example.  If you wrote a generic "popStack" function, which takes an  
array, knowing before popping that you have control of the block is  
important (you may not call assumeSafeAppend if your pre-pop capacity was  
0).

> One caveat about this method: If you save a slice of the stack, pop  
> elements off the stack, and then push new values back on, the old slice  
> you took will likely [4] reflect the new values, not the original ones.
...
> [4] I say "likely" instead of "definitely" because of an unfortunate  
> indeterminism inherent in D's array/slice system. This quirk is  
> explained in the "Determinism" section of Steven Schveighoffer's article  
> mentioned above.

Actually, with the new functions capacity, assumeSafeAppend, and reserve,  
most of the "non-determinism" is mitigated.  In your case, however, you  
know you have control of the stack, and all its data, popping and pushing  
will *definitely* overwrite the old value.

-Steve


More information about the Digitalmars-d mailing list