使用allocator实现自己的低配Vector:
提示:主要是使用下allocator:
allocator中使用四大件:
1、construct(对象的创建)
2、allocate(空间的申请)
3、destroy(对象的销毁)
4、deallocate(对象空间的释放)
实现代码
#include <iostream>
#include <memory>
using std::allocator;
using std::cout;
using std::endl;
using std::uninitialized_copy;
template<typename T>
class Vector
{
public:
Vector();
~Vector();
void push_back(const T &);
void pop_back();
int size();
int capacity();
const T & operator[](int idsx) const;
private:
void reallocate();//重新分配内存,动态扩容要用的
private:
static std::allocator<T> _alloc;
T *_start; //指向数组中的第一个元素
T *_finish; //指向最后一个实际元素之后的那个元素
T *_end_of_storage; //指向数组本身之后的位置
};
template<typename T>
allocator<T> Vector<T>:: _alloc;
template <typename T>
Vector<T>::Vector()
:_start(0)
,_finish(0)
,_end_of_storage(0)
{
cout << "Vector()" << endl;
}
template <typename T>
Vector<T>::~Vector()
{
cout << "~Vector()" << endl;
if(_start)
{
while(_start != _finish)
{
_alloc.destroy(--_finish);
}
_alloc.deallocate(_start,capacity());
}
}
template <typename T>
int Vector<T>::size()
{
return _finish - _start;
}
template <typename T>
int Vector<T>::capacity()
{
return _end_of_storage - _start;
}
template <typename T>
void Vector<T>::push_back(const T &rhs)
{
if(size() == capacity())
{
cout << "capacity is not enough , allocate new memory" << endl;
reallocate();
}
_alloc.construct(_finish++,rhs);
}
template <typename T>
void Vector<T>::pop_back()
{
if(size() == 0)
{
cout << "memory is empty" << endl;
return;
}else{
_alloc.destroy(--_finish);
}
}
template<typename T>
void Vector<T>::reallocate()
{
int oldsize = capacity();
int newsize = (oldsize == 0 ? 1 : oldsize * 2);
//1、分配新空间
T * newelem = _alloc.allocate(newsize);
if(_start)
{
//2、将原始空间的内容复制过来
uninitialized_copy(_start, _finish, newelem);
//3、销毁原始空间对象
while(_start != _finish)
{
_alloc.destroy(--_finish);
}
//4、释放内存
_alloc.deallocate(_start,capacity());
}
//5、更新新空间
_start = newelem;
_finish = newelem + oldsize;
_end_of_storage = newelem + newsize;
}
template <typename T>
const T& Vector<T>::operator[](int idx)const
{
return _start[idx];
}
template <typename T>
void display(Vector<T>& rhs)
{
for(int idx = 0; idx < rhs.size(); ++idx)
{
cout << rhs[idx] << " ";
}
cout << endl;
}
void test()
{
Vector<int> v1;
cout << "v1空间大小:" << v1.size();
cout << endl;
cout << "v1申请内存的空间的大小:" << v1.capacity();
cout << endl << endl;
cout << "执行插入1、2、3、4、5" << endl;
v1.push_back(1);
v1.push_back(2);
v1.push_back(3);
v1.push_back(4);
v1.push_back(5);
cout << "打印容器内容:" << endl;
display(v1);
cout << endl << "执行弹出操作" << endl;
v1.pop_back();
cout << "打印容器内容:" << endl;
display(v1);
}
int main()
{
test();
return 0;
}