据我了解,自定义分配器必须符合分配器概念的要求。但是,基于该界面,当向量用完储备时,我看不到如何选择新的分配量。
例如,我机器上的当前实现每次reserve
在push_back()
. 我想提供一个缓慢且具有内存意识的自定义分配器。它只会分配以前capacity+1
的元素来容纳新元素。
这些是我正在查看的概念的接口:
a.allocate(n)
a.allocate(n, cvptr) (optional)
我制作了一个像这样的工作样板分配器:
#include <limits>
#include <iostream>
template <class T> class MyAlloc {
public:
// type definitions
typedef T value_type;
typedef T *pointer;
typedef const T *const_pointer;
typedef T &reference;
typedef const T &const_reference;
typedef std::size_t size_type;
typedef std::ptrdiff_t difference_type;
pointer address(reference value) const {
return &value;
}
const_pointer address(const_reference value) const {
return &value;
}
size_type max_size() const throw() {
return std::numeric_limits<std::size_t>::max() / sizeof(T);
}
pointer allocate(size_type num, const void * = 0) {
return (pointer)(::operator new(num * sizeof(T)));
}
void construct(pointer p, const T &value) {
new ((void *)p) T(value);
}
void destroy(pointer p) {
p->~T();
}
void deallocate(pointer p, size_type num) {
::operator delete((void *)p);
}
};
看allocate
功能:
pointer allocate(size_type num, const void * = 0) {
return (pointer)(::operator new(num * sizeof(T)));
}
我可以在这里分配更多或更少的内存,但我没有看到一种将其报告回向量的方法,以便它知道它的当前容量是多少。
也许这超出了分配器的责任范围?