View source code Display the source code in object.d from which this page was generated on github. Improve this page Quickly fork, edit online, and submit a pull request for this page. Requires a signed-in GitHub account. This works well for small changes. If you'd like to make larger changes you may want to consider using local clone. Page wiki View or edit the community-maintained wiki page associated with this page.

Function object.reserve

Reserves capacity for a slice. The capacity is the size that the slice can grow to before the underlying array must be reallocated or extended.

The return value is the new capacity of the array (which may be larger than the requested capacity).

Prototype

size_t reserve(T)(
  T[] arr,
  size_t newcapacity
) pure nothrow @trusted;

Example

//Static array slice: no capacity. Reserve relocates.
int[4] sarray = [1, 2, 3, 4];
int[]  slice  = sarray[];
auto u = slice.reserve(8);
assert(u >= 8);
assert(sarray.ptr !is slice.ptr);
assert(slice.capacity == u);

//Dynamic array slices
int[] a = [1, 2, 3, 4];
a.reserve(8); //prepare a for appending 4 more items
auto p = a.ptr;
u = a.capacity;
a ~= [5, 6, 7, 8];
assert(p == a.ptr);      //a should not have been reallocated
assert(u == a.capacity); //a should not have been extended

Authors

Walter Bright, Sean Kelly

License

Boost License 1.0.

Comments