基于malloc/free的STL分配器
malloc/free based STL allocator
STL中是否存在基于malloc/free的分配器?如果没有,有人知道简单的复制/粘贴吗?我需要一个不能调用new/delete的地图。
首先,我要注意的是,更改映射本身的分配器不会更改存储在映射中的对象所使用的分配。例如,如果您执行以下操作:
std::map<std::string, int, my_allocator<std::pair<const std::string, int> > m;
映射本身将使用指定的分配器来分配内存,但当映射中的std::string
分配内存时,他们仍然会使用默认的分配器(它将使用new
和delete
。因此,如果您通常需要避免使用new
和delete
,您必须确保映射本身不仅使用正确的分配器,而且它存储的任何对象都使用相同的分配器(我知道这可能说明了显而易见的问题,但我忽略了它,所以也许值得一提)。
附带条件,代码:
#ifndef ALLOCATOR_H_INC_
#define ALLOCATOR_H_INC_
#include <stdlib.h>
#include <new>
#include <limits>
namespace JVC {
template <class T>
struct allocator {
typedef size_t size_type;
typedef ptrdiff_t difference_type;
typedef T* pointer;
typedef const T* const_pointer;
typedef T& reference;
typedef const T& const_reference;
typedef T value_type;
template <class U> struct rebind { typedef allocator<U> other; };
allocator() throw() {}
allocator(const allocator&) throw() {}
template <class U> allocator(const allocator<U>&) throw(){}
~allocator() throw() {}
pointer address(reference x) const { return &x; }
const_pointer address(const_reference x) const { return &x; }
pointer allocate(size_type s, void const * = 0) {
if (0 == s)
return NULL;
pointer temp = (pointer)malloc(s * sizeof(T));
if (temp == NULL)
throw std::bad_alloc();
return temp;
}
void deallocate(pointer p, size_type) {
free(p);
}
size_type max_size() const throw() {
return std::numeric_limits<size_t>::max() / sizeof(T);
}
void construct(pointer p, const T& val) {
new((void *)p) T(val);
}
void destroy(pointer p) {
p->~T();
}
};
}
#endif
还有一个测试代码:
#include <map>
#include <vector>
#include <iostream>
#include <string>
#include <iterator>
#include "allocator.h"
// Technically this isn't allowed, but it's only demo code, so we'll live with it.
namespace std {
std::ostream &operator<<(std::ostream &os, std::pair<std::string, int> const &c) {
return os << c.first << ": " << c.second;
}
}
int main() {
std::map<std::string, int, std::less<std::string>,
JVC::allocator<std::pair<const std::string, int> > > stuff;
stuff["string 1"] = 1;
stuff["string 2"] = 2;
stuff["string 3"] = 3;
std::copy(stuff.begin(), stuff.end(),
std::ostream_iterator<std::pair<std::string, int> >(std::cout, "n"));
return 0;
}
事实上,正如@MichaelBurr所建议的,Stephen J,Lavavej的"mallocator"就是你想要的。我今天刚刚在@Arnaud的回答中得到了更新和美化的代码,请看一看。
相关文章:
- C++ MSVC 中的自定义 STL 分配器错误?
- C 中STL地图的自定义分配器
- 为什么STL保留分配器的接口
- 是一个const t的STL容器,具有定制分配器不正确的
- 不匹配的 std::某些 STL 容器的分配器
- 重写 C++ STL 分配器函数以将其包装为线程安全
- 使固定大小的块池分配器适应某些STL容器
- 带有 STL 向量的模板函数会因新的分配器而中断
- 比较使用不同分配器的STL字符串
- 分配嵌套 STL 容器时使用哪个分配器
- 自定义分配器有时会与stl向量一起崩溃
- 进程间共享内存的非Boost STL分配器
- 是否可以编写一个自定义 STL 分配器,该分配器使用指向用户提供的分配函数的指针
- 除了默认分配器之外,stl现在还有其他分配器吗
- C++自定义分配器和STL容器
- 基于malloc/free的STL分配器
- 默认stl分配器如何分配
- 自定义 STL 分配器会导致删除第一个字符
- 替换默认的STL分配器
- STL分配器复制构造函数需求的目的是什么?