Getting std::map allocator to work
Asked Answered
B

2

7

I've got an extremely basic 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;
    };
};

Which works fine when I use it with: "std::vector >", however, when I try use it with an std::map like:

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;
}

It fails to compile (gcc 4.6) giving an extremely long error ending with: /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&)’

Brabant answered 9/6, 2011 at 16:33 Comment(1)
Why do you think you need a custom allocator?Ardith
M
16

Because allocator is 4th template parameter, whereas 3rd parameter is comparator like std::less? so std::map<int, int, std::less<int>, Allocator< std::pair<const int, int> > > should work.

Also I think you should add default ctor and copy ctor:

  Allocator() {}

  template<class Other>
  Allocator( const Allocator<Other>& _Right ) {}
Menendez answered 9/6, 2011 at 16:48 Comment(2)
+1 for getting all things right. just a nit - no need for default constructorSulphanilamide
That's a generic conversion constructor, not a copy constructor. But the default constructor is needed…Stanza
G
1

In case if someone is looking for the generalized way:

template<class Key, class T,class Compare = std::less<Key>, class _Ax = Allocator<std::pair<const Key, T> >>
class Map : public std::map<Key, T, Compare, _Ax >
{
};

Then use it,

Map<int,char> myMap;
myMap.insert<std::pair<int,char>(1,'o');
Gawain answered 5/2, 2018 at 17:6 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.