ensure safety of std::move

This commit is contained in:
2024-02-26 00:32:47 +00:00
parent 4ca636eb8f
commit 847a48dcda

View File

@ -276,6 +276,24 @@ class vector {
}
return *this;
}
vector &operator=(vector &&other) noexcept {
if (this == &other) return *this;
if (raw_beg != nullptr) {
for (size_t i = 0; i < current_length; ++i) {
std::allocator_traits<decltype(alloc)>::destroy(alloc, raw_beg + i);
}
alloc.deallocate(raw_beg, allocated_length);
}
raw_beg = other.raw_beg;
raw_end = other.raw_end;
allocated_length = other.allocated_length;
current_length = other.current_length;
other.raw_beg = nullptr;
other.raw_end = nullptr;
other.allocated_length = 0;
other.current_length = 0;
return *this;
}
/**
* assigns specified element with bounds checking
* throw index_out_of_bound if pos is not in [0, size)
@ -340,11 +358,13 @@ class vector {
* clears the contents
*/
void clear() {
for (size_t i = 0; i < current_length; ++i) {
alloc.destroy(raw_beg + i);
if (raw_beg != nullptr) {
for (size_t i = 0; i < current_length; ++i) {
alloc.destroy(raw_beg + i);
}
current_length = 0;
alloc.deallocate(raw_beg, allocated_length);
}
current_length = 0;
alloc.deallocate(raw_beg, allocated_length);
raw_beg = alloc.allocate(1);
raw_end = raw_beg;
allocated_length = 1;
@ -504,7 +524,7 @@ class vector {
}
}
};
template<typename T>
template <typename T>
std::allocator<T> vector<T>::alloc;
} // namespace sjtu