@@ -763,14 +763,32 @@ $(H3 $(LNAME2 capacity-reserve, `capacity` and `reserve`))
763
763
GC-allocated memory, the capacity will be zero.
764
764
The spare capacity for an array *a* is `a.capacity - a.length`.)
765
765
766
+ $(P By default, `capacity` will be zero if an element has been stored after the slice.)
767
+
768
+ $(SPEC_RUNNABLE_EXAMPLE_RUN
769
+ ---
770
+ int[] a;
771
+ assert(a.capacity == 0);
772
+ a.length = 3; // may allocate spare capacity too
773
+ assert(a.capacity >= 3);
774
+ auto b = a[1..3];
775
+ assert(b.capacity >= 2); // either a or b can append into any spare capacity
776
+ b = a[0..2];
777
+ assert(b.capacity == 0);
778
+ ---
779
+ )
780
+
781
+ $(RATIONALE This behaviour helps prevent accidental overwriting of
782
+ elements in another slice. It is also necessary to protect immutable
783
+ elements from being overwritten.)
784
+
766
785
$(P The $(D reserve)
767
786
function expands an array's capacity for use by the
768
787
$(RELATIVE_LINK2 array-appending, append operator) or `.length` assignment.)
769
788
770
789
$(SPEC_RUNNABLE_EXAMPLE_RUN
771
790
---------
772
791
int[] array;
773
- assert(array.capacity == 0);
774
792
const size_t cap = array.reserve(10); // request
775
793
assert(cap >= 10); // allocated may be more than request
776
794
assert(array.ptr != null);
@@ -791,21 +809,24 @@ assert(copy.ptr != array.ptr);
791
809
is the address of `array[0]`. So `copy.capacity` will be zero to
792
810
prevent any appending to `copy` from overwriting elements in `array`.)
793
811
794
- $(NOTE The runtime uses the number of elements appended to track the
812
+ $(NOTE The runtime uses the number of appended elements to track the
795
813
start of the spare capacity for the memory allocation.)
796
814
797
815
$(P When an array with spare capacity has its length reduced, or is
798
816
assigned a slice of itself that ends before the previous last element,
799
817
the capacity will be zero.)
800
818
819
+ $(P The `@system` function $(REF1 assumeSafeAppend, object) allows the
820
+ capacity to be regained, but care must be taken not to overwrite
821
+ immutable elements that may exist in a longer slice.)
822
+
801
823
$(SPEC_RUNNABLE_EXAMPLE_RUN
802
824
---
803
825
int[] a = [1, 2, 3];
804
- a.reserve(2);
805
- a = a[];
806
- assert(a.capacity > 0);
807
- a = a[0..2];
826
+ a.length--;
808
827
assert(a.capacity == 0);
828
+ a.assumeSafeAppend();
829
+ assert(a.capacity >= 3);
809
830
---
810
831
)
811
832
0 commit comments