Skip to content

Commit 408a15b

Browse files
authored
Fix SmallVector's resize() method (#4979)
A resize from a large amount to a small amount would sometimes not clear the flexible storage, if we used it before but not after.
1 parent 7fb4481 commit 408a15b

File tree

2 files changed

+37
-0
lines changed

2 files changed

+37
-0
lines changed

src/support/small_vector.h

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -116,6 +116,8 @@ template<typename T, size_t N> class SmallVector {
116116
usedFixed = std::min(N, newSize);
117117
if (newSize > N) {
118118
flexible.resize(newSize - N);
119+
} else {
120+
flexible.clear();
119121
}
120122
}
121123

test/example/small_vector.cpp

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -66,12 +66,47 @@ template<typename T> void test(size_t N) {
6666
t.reserve(t.capacity() + 100);
6767
assert(t.capacity() >= N + 100);
6868
}
69+
{
70+
// Test resizing.
71+
T t;
72+
73+
assert(t.empty());
74+
t.resize(1);
75+
assert(t.size() == 1);
76+
t.resize(2);
77+
assert(t.size() == 2);
78+
t.resize(3);
79+
assert(t.size() == 3);
80+
t.resize(6);
81+
assert(t.size() == 6);
82+
83+
// Now go in reverse.
84+
t.resize(6);
85+
assert(t.size() == 6);
86+
t.resize(3);
87+
assert(t.size() == 3);
88+
t.resize(2);
89+
assert(t.size() == 2);
90+
t.resize(1);
91+
assert(t.size() == 1);
92+
93+
// Test a big leap from nothing (rather than gradual increase as before).
94+
t.clear();
95+
assert(t.empty());
96+
t.resize(6);
97+
assert(t.size() == 6);
98+
t.resize(2);
99+
assert(t.size() == 2);
100+
t.clear();
101+
assert(t.empty());
102+
}
69103
}
70104

71105
int main() {
72106
test<SmallVector<int, 0>>(0);
73107
test<SmallVector<int, 1>>(1);
74108
test<SmallVector<int, 2>>(2);
109+
test<SmallVector<int, 3>>(3);
75110
test<SmallVector<int, 10>>(10);
76111
std::cout << "ok.\n";
77112
}

0 commit comments

Comments
 (0)