文章目录
【1】先简单实现一个空间配置器Allocator
template<typename T>
struct Allocator
{
T* allocate(size_t size) // 负责内存开辟
{
return (T*)malloc(sizeof(T) * size);
}
void deallocate(void *p) // 负责内存释放
{
free(p);
}
void construct(T *p, const T &val) // 负责对象构造
{
new (p) T(val); // 定位new
}
void destroy(T *p) // 负责对象析构
{
p->~T(); // ~T()代表了T类型的析构函数
}
};
【2】自己实现一个简单的vector容器
/****************************************************************************
=============================================================================
注意:容器底层凡是涉及内存开辟,内存释放,对象构造和析构,都通过allocator空间配置器来实现
=============================================================================
****************************************************************************/
template<typename T, typename Alloc = Allocator<T>>
class vector
{
public:
vector(int size = 10)
{
// 需要把内存开辟和对象构造分开处理
//_first = new T[size];
_first = _allocator.allocate(size);
_last = _first;
_end = _first + size;
}
~vector()
{
// 析构容器有效的元素,然后释放_first指针指向的堆内存
// 非delete[]_first;
for (T *p = _first; p != _last; ++p)
{
_allocator.destroy(p); // 把_first指针指向的数组的有效元素进行析构操作
}
_allocator.deallocate(_first); // 释放堆上的数组内存
_first = _last = _end = nullptr;
}
vector(const vector<T> &rhs) //拷贝构造函数
{
int size = rhs._end - rhs._first;
//非_first = new T[size];
_first = _allocator.