Vector在创建时接受的参数
在c++STL中,容器类vector实际上在创建时可以接收两个参数,第一个是存储的元素的类型,第二个是内存配置器,第二个参数有默认值,但我们可以覆盖这个默认值,但是默认值的覆盖需要遵守一些规则,而这些规则则是本文的要讲述的。
创建时添加第二参数:std::vector<int, my::allocator<int>> iv; //创建一个元素类型为int,内存配置器为my空间下的allocator<int>类
简易内存配置器
#include <cstddef>
#include <cstdlib>
#include <climits>
namespace my{
template<class T>
class allocator{
public:
//以下的 typedef 是必须的,因为在容器中有类似 _alloc::pointer 的语法
typedef T value_type;
typedef T* pointer;
typedef const T* const_pointer;
typedef const T& const_reference;
typedef T& reference;
typedef size_t size_type;
typedef ptrdiff_t difference_type;
//rebind, 一般情况下似乎可以去掉,暂不知道在什么场景下使用
template <class U>
struct rebind{
typedef allocator<U> other;
};
//以下全部的方法都可无,而这取决于容器执行了什么操作
pointer allocate(size_type n, const void * hint = 0){
return (T*)malloc(n * sizeof(T));
//return (T*)(::operator new((size_t)(size * sizeof(T))));
}
void deallocate(pointer p, size_type n){
delete(p);
//free(p);
}
void construct(pointer p, const T& value){
new(p) T(value);
}
void destroy(pointer p){
p->~T();
}
pointer address(reference x){
return (pointer)&x;
}
const_pointer const_address(const_reference x){
return (const_pointer)&x;
}
size_type max_size() const {
return size_type(UINT_MAX/sizeof(T));
}
};
}
//简易测试
#include <iostream>
#include <vector>
using namespace std;
int main(){
int a[5] = {1,2,3,4,5};
std::vector<int, my::allocator<int>> iv(a, a+5);
iv.push_back(1);
for(int i = 0; i < 6; ++i)
std::cout << iv[i] << std::endl;
}
内存配置器的接口
接口名 | 参数 | 返回值 | 功能 |
allocate |
size_type n 元素个数, const void *p = 0 类型指针,似乎可以可无 |
pointer | 分配可容纳n个元素的空间 |
deallocate |
pointer p 指向元素的指针, size_type n 释放的个数,其实在调用free时不需要 |
void | 释放空间 |
destroy | pointer p 指向元素的指针 | void | 销毁元素, |
construct |
pointer p, const T& value |
void | 构造元素,但是不配置空间 |
address | reference x | pointer |
获取元素的地址相当于&x |
const_address | const_reference x | const_pointer | 获取元素的地址,针对常量元素 |
max_size | void | size_type | 可容的元素数量最大值 |