diff --git a/vector/src/vector.hpp b/vector/src/vector.hpp index 5a2d88a..692261c 100644 --- a/vector/src/vector.hpp +++ b/vector/src/vector.hpp @@ -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::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 +template std::allocator vector::alloc; } // namespace sjtu