Tre*_*key 1 c++ memory-management vector allocator c++-concepts
据我了解,自定义分配器必须符合分配器概念的要求。但是,基于该界面,我看不出当向量耗尽储备时我将如何选择新的分配量。
例如,我机器上的当前实现每次reserve在push_back(). 我想提供一个速度慢且内存敏感的自定义分配器。它只会分配前一个capacity+1来容纳新元素。
这些是我正在研究的概念的接口:
a.allocate(n)
a.allocate(n, cvptr) (optional)
Run Code Online (Sandbox Code Playgroud)
我制作了一个工作样板分配器,如下所示:
#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);
}
};
Run Code Online (Sandbox Code Playgroud)
看allocate函数:
pointer allocate(size_type num, const void * = 0) {
return (pointer)(::operator new(num * sizeof(T)));
}
Run Code Online (Sandbox Code Playgroud)
我可以在这里分配更多或更少的内存,但我没有看到一种将其报告回向量的方法,以便它知道其当前容量是多少。
也许这超出了分配器的责任?
C++ 继承的 STL 模型基于容器和分配器之间的特定划分。分配器的目的是提供某人请求的内存。分配多少内存的决定完全取决于容器,而不考虑它使用哪个分配器来提供该内存。
这就是 C++ 使用的模型。您可以编写自己的vector类似容器,允许其分配器指定应该分配多少。但除此之外,没有。