[英]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
s分配內存時,它們仍將使用默認分配器(將使用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所說,Lavavej的'mallocator'是你正在尋找的。 我今天剛剛在@Arnaud的答案中得到了更新和漂亮的代碼,請看看。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.