| 156 | /*************** vector 类模板 ****************/ |
| 157 | template<typename T, typename Alloc = Allocator<T>> |
| 158 | class Vector |
| 159 | { |
| 160 | public: |
| 161 | Vector(int size = 10) |
| 162 | { |
| 163 | // 需要把内存开辟和对象构造分开处理, 不能是直接 _first = new T[size] |
| 164 | // 因为 new 既分配空间又会调用相应的构造函数, 实际上这里只需要分配空间 |
| 165 | _first = _allocator.allocate(size); |
| 166 | _last = _first; |
| 167 | _end = _first + size; |
| 168 | } |
| 169 | |
| 170 | ~Vector() |
| 171 | { |
| 172 | // 析构容器的有效元素,然后释放 _first 指针指向的堆内存 |
| 173 | for (T *p = _first; p != _last; ++ p) |
| 174 | { |
| 175 | _allocator.destroy(p); // 把 _first 指针指向的数组的有效元素进行析构 |
| 176 | } |
| 177 | _allocator.deallocate(_first); // 释放堆上的数组内存 |
| 178 | _first = _last = _end = nullptr; |
| 179 | } |
| 180 | |
| 181 | Vector(const Vector<T> &rhs) |
| 182 | { |
| 183 | int size = rhs._end - rhs._first; |
| 184 | _first = _allocator.allocate(size); // 分配 size 大小内存 |
| 185 | int len = rhs._last - rhs._first; |
| 186 | for (int i = 0; i < len; ++ i) { // 构造 len 个有效的T对象 |
| 187 | _allocator.construct(_first + i, rhs.first[i]); |
| 188 | } |
| 189 | _last = _first + len; |
| 190 | _end = _first + size; |
| 191 | } |
| 192 | |
| 193 | Vector<T>& operator=(const Vector<T> &rhs) |
| 194 | { |
| 195 | if (this == &rhs) return *this; |
| 196 | |
| 197 | for (T *p = _first; p != _last; ++ p) // 析构有效对象 |
| 198 | { |
| 199 | _allocator.destroy(p); |
| 200 | } |
| 201 | _allocator.deallocate(_first); // 释放所有内存 |
| 202 | |
| 203 | int size = rhs._end - rhs._first; |
| 204 | _first = _allocator.allocate(size); // 分配 size 大小内存 |
| 205 | |
| 206 | int len = rhs._last - rhs._first; |
| 207 | for (int i = 0; i < len; ++ i) // 构造 len 个有效的T对象 |
| 208 | { |
| 209 | _allocator.construct(_first + i, rhs.first[i]); |
| 210 | } |
| 211 | _last = _first + len; |
| 212 | _end = _first + size; |
| 213 | } |
| 214 | |
| 215 | // void push_back(const T& val) // 向容器末尾添加元素 |
nothing calls this directly
no test coverage detected