让std :: map allocator工作

Hep*_*tic 7 c++ stl allocator

我有一个非常基本的分配器:

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;
    };
};
Run Code Online (Sandbox Code Playgroud)

当我使用它时,它工作正常:"std :: vector>",但是,当我尝试将它与std :: map一起使用时:

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;
}
Run Code Online (Sandbox Code Playgroud)

它无法编译(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&)’

pur*_*ess 16

因为allocator是第4个模板参数,而第3个参数是比较器std::less吗?所以std::map<int, int, std::less<int>, Allocator< std::pair<const int, int> > >应该工作.

另外我认为你应该添加默认的ctor和copy ctor:

  Allocator() {}

  template<class Other>
  Allocator( const Allocator<Other>& _Right ) {}
Run Code Online (Sandbox Code Playgroud)

  • +1让所有事情都正确.只是一个尼特 - 不需要默认构造函数 (3认同)
  • 这是一个通用的转换构造函数,而不是一个复制构造函数.但是需要默认的构造函数...... (3认同)