Changed C++'s SharedVector::clear() to not preserve capacity when shared

This commit is contained in:
Simon Hausmann 2021-08-12 12:09:40 +02:00 committed by Simon Hausmann
parent d65af654d7
commit a752c798b8
2 changed files with 8 additions and 6 deletions

View file

@ -130,10 +130,9 @@ struct SharedVector
/// Clears the vector and removes all elements. The capacity remains unaffected.
void clear()
{
// Detach first to retain capacity, so that the begin() call doesn't detach
// (which it would to inner->size instead of capacity)
detach(inner->capacity);
{
if (inner->refcount != 1) {
*this = SharedVector();
} else {
auto b = begin(), e = end();
inner->size = 0;
for (auto it = b; it < e; ++it) {

View file

@ -100,6 +100,7 @@ TEST_CASE("SharedVector")
using namespace sixtyfps;
SharedVector<SharedString> vec;
vec.clear();
vec.push_back("Hello");
vec.push_back("World");
vec.push_back("of");
@ -112,11 +113,13 @@ TEST_CASE("SharedVector")
REQUIRE(orig_cap >= vec.size());
vec.clear();
REQUIRE(vec.size() == 0);
REQUIRE(vec.capacity() == orig_cap);
REQUIRE(vec.capacity() == 0); // vec was shared, so start with new empty vector.
vec.push_back("Welcome back");
REQUIRE(vec.size() == 1);
REQUIRE(vec.capacity() == orig_cap);
REQUIRE(vec.capacity() >= vec.size());
REQUIRE(copy.size() == 4);
REQUIRE(copy.capacity() == orig_cap);
copy.clear(); // copy is not shared (anymore), retain capacity.
REQUIRE(copy.capacity() == orig_cap);
}