On Saturday, May 02, 2015 07:46:27 Ali Çehreli via Digitalmars-d-learn wrote: > On 05/02/2015 01:56 AM, Jonathan M Davis via Digitalmars-d-learn wrote: > > > I really don't think that it's reasonable in the general case to > expect to > > be able to guarantee that the capacity of a dynamic array won't change. > > Yes, it is very different from other languages like C and C++ that > talking about this behavior is worth it.
It really comes down to how the memory itself is owned and managed, and with dynamic arrays, it's the runtime that does that, and dynamic arrays simply don't own or manage their memory, so expecting to them to isn't going to work. > The elements are const, the slice is passed by value, but the reserved > capacity disappears: > > void foo(const(int)[] b) > { > b ~= 42; > } > > a.reserve(milllllion); > assert(a.capacity >= milllllion); > > foo(a); > assert(a.capacity == 0); // WAT Yeah. If you just code in a way that you're making sure that you're not slicing an array and then appending to the slices, then you can rely on reserve working as you'd expect, and situations like this work just fine int[] foo; foo.reserve(target); while(blah) { //... foo ~= next; //... } so long as you're not doing anything else with the array in the process, but if you start passing a dynamic array around to functions which might append to it or a to a slice of it, then all bets are off. I really don't think that it's an issue in general, but if you do want to guarantee that nothing affects the capacity of your array, then you're going to need to either wrap all access to it so that nothing else can actually get at a slice of the array itself, or you need to use another container - one which is actually a container rather than the weird half-container, half-iterator/range construct that a D dynamic array is. Ultimately, I think that the semantics of D arrays make sense and are extremely useful, but they are definitely weird in comparison to pretty much anything else that you're going to run into. - Jonathan M Davis