我有一個非常基本的分配:獲得的std ::地圖分配器工作
template<typename T>
struct Allocator : public std::allocator<T> {
inline typename std::allocator<T>::pointer allocate(typename std::allocator<T>::size_type n, typename std::allocator<void>::const_pointer = 0) {
std::cout << "Allocating: " << n << " itens." << std::endl;
return reinterpret_cast<typename std::allocator<T>::pointer>(::operator new(n * sizeof (T)));
}
inline void deallocate(typename std::allocator<T>::pointer p, typename std::allocator<T>::size_type n) {
std::cout << "Dealloc: " << n << " itens." << std::endl;
::operator delete(p);
}
template<typename U>
struct rebind {
typedef Allocator<U> other;
};
};
當我用它工作正常「的std ::矢量>」,但是,當我嘗試使用它用的std ::地圖這樣的:
int main(int, char**) {
std::map<int, int, Allocator< std::pair<const int, int> > > map;
for (int i(0); i < 100; ++i) {
std::cout << "Inserting the " << i << " item. " << std::endl;
map.insert(std::make_pair(i*i, 2*i));
}
return 0;
}
它無法編譯器(gcc 4.6),給出一個非常長的錯誤結尾:/usr/lib/gcc/x86_64-redhat-linux/4.6.0/../../../../include/c++/4.6.0/bits/stl_tree.h:959:25: error: no match for call to ‘(Allocator<std::pair<const int, int> >) (std::pair<const int, int>::first_type&, const int&)’
爲什麼你認爲你需要一個自定義分配器? – 2011-06-09 16:47:21