[rust-dev] problems with adding an element to a ' @' vector.
pwalton at mozilla.com
Mon Dec 10 16:03:00 PST 2012
On 12/10/12 3:49 PM, arkaitzj at gmail.com wrote:
> Aren't both ~vector and @vector dynamic memory? why can we append to a
> ~vector but not to a @vector?
Because the pointer points to an object that looks like this:
---> [ length ] [ element 1 ] [ element 2 ] [ element 3 ]
Now suppose that the allocator didn't leave any room for more elements
after it. In general we have to assume this, because we can't leave an
infinite amount of space after our arrays. Thus in general appending to
a vector requires reallocating the entire vector and move it to some new
location in memory. The problem is that, after we do that, we have to
update all the pointers to point to the new location.
In the case of ~[T] this is easy. There is only one pointer, and it was
passed into push(), so we can just update it. With @[T] it's not so easy
though. We have no idea at compile time how many pointers there are to
the vector, and even at runtime finding all the pointers and updating
them would be a quite complex and expensive operation. So we have to
copy the array.
More information about the Rust-dev