Vector源码实现
vector是STL里最常用的容器,本文尝试着用一种相对简单的方法构建一个vector实现模板,并加上std::allocator。尽可能解释其中函数的意义。
代码实现
用一个testAllocator继承allocator。此处特化int版本。
#ifndef __TEST_H__
#define __TEST_H__
#include <memory>
#include <iostream>
class testAllocator : public std::allocator<int> {
public:
typedef std::allocator<int> Base;
// 此函数就是new功能。真正分配内存。
int * allocate(std::size_t size) {
std::cout << "Test Allocator: allocate" << std::endl;
return Base::allocate(size);
}
// delete功能。真正释放内存。
void deallocate(int * p, std::size_t size) {
std::cout << "Test Allocator: deallocate" << std::endl;
Base::deallocate(p, size);
}
// 此函数不释放内存,只赋值。
void construct(int * p, int val) {
std::cout << "Test Allocator: Construct, value: " << val
<< std::endl;
Base::construct(p, val);
}
// 此函数不释放内存,只把值丢去。
void destroy(int * p) {
std::cout << "Test Allocator: Destroy, value: " << *p << std::endl;
Base::destroy(p);
}
};
#endif
#ifndef __VECTOR_H__
#define __VECTOR_H__
#define _a Alloc()
#include "base.h"
#include <memory>
template< typename T, typename Alloc = std::allocator<T> >
class myVector : public Base {
public:
// Constructor
myVector() {
_data = _a.allocate(1);
_size = 0;
_capacity = 1;
}
myVector(const std::size_t & size, const T & val,
Alloc a = Alloc()) {
_data = a.allocate(size);
for (std::size_t i = 0; i < size; ++i)
a.construct(_data + i, val);
_size = _capacity = size;
}
template<typename InputIterator>
myVector(InputIterator begin, InputIterator end,
Alloc a = Alloc()) {
_size = _capacity = end - begin;
_data = a.allocate(_size);
std::size_t cnt = 0;
for (InputIterator it = begin; it != end; ++it)
a.construct(_data + (cnt++), *it);
}
myVector(const myVector & other) {
_size = other._size;
_capacity = other._capacity;
_data = _a.allocate(_capacity);
for (std::size_t i = 0; i < _size; ++i)
_a.construct(_data + i, other._data[i]);
}
// Destructor
~myVector() {
for (std::size_t i = 0; i < _size; ++i)
_a.destroy(_data + i);
if (_capacity > 0)
_a.deallocate(_data, _capacity);
}
// Copy Operator