Skip to content

Commit dde9477

Browse files
authored
[NFC] Use unique_ptr in SparseSet (#116617)
This allows implementing the move constructor.
1 parent cac1360 commit dde9477

File tree

2 files changed

+20
-4
lines changed

2 files changed

+20
-4
lines changed

llvm/include/llvm/ADT/SparseSet.h

Lines changed: 8 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -129,7 +129,12 @@ class SparseSet {
129129
using DenseT = SmallVector<ValueT, 8>;
130130
using size_type = unsigned;
131131
DenseT Dense;
132-
SparseT *Sparse = nullptr;
132+
133+
struct Deleter {
134+
void operator()(SparseT *S) { free(S); }
135+
};
136+
std::unique_ptr<SparseT[], Deleter> Sparse;
137+
133138
unsigned Universe = 0;
134139
KeyFunctorT KeyIndexOf;
135140
SparseSetValFunctor<KeyT, ValueT, KeyFunctorT> ValIndexOf;
@@ -144,7 +149,7 @@ class SparseSet {
144149
SparseSet() = default;
145150
SparseSet(const SparseSet &) = delete;
146151
SparseSet &operator=(const SparseSet &) = delete;
147-
~SparseSet() { free(Sparse); }
152+
SparseSet(SparseSet &&) = default;
148153

149154
/// setUniverse - Set the universe size which determines the largest key the
150155
/// set can hold. The universe must be sized before any elements can be
@@ -159,11 +164,10 @@ class SparseSet {
159164
// Hysteresis prevents needless reallocations.
160165
if (U >= Universe/4 && U <= Universe)
161166
return;
162-
free(Sparse);
163167
// The Sparse array doesn't actually need to be initialized, so malloc
164168
// would be enough here, but that will cause tools like valgrind to
165169
// complain about branching on uninitialized data.
166-
Sparse = static_cast<SparseT*>(safe_calloc(U, sizeof(SparseT)));
170+
Sparse.reset(static_cast<SparseT *>(safe_calloc(U, sizeof(SparseT))));
167171
Universe = U;
168172
}
169173

llvm/unittests/ADT/SparseSetTest.cpp

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -204,4 +204,16 @@ TEST(SparseSetTest, PopBack) {
204204
for (unsigned i = 0; i < UpperBound; ++i)
205205
ASSERT_TRUE(Set.insert(i).second);
206206
}
207+
208+
TEST(SparseSetTest, MoveConstructor) {
209+
USet Set;
210+
Set.setUniverse(2);
211+
Set.insert(1);
212+
EXPECT_FALSE(Set.empty());
213+
// Move and check original is empty.
214+
USet OtherSet(std::move(Set));
215+
EXPECT_TRUE(Set.empty());
216+
EXPECT_TRUE(OtherSet.contains(1));
217+
}
218+
207219
} // namespace

0 commit comments

Comments
 (0)