user4362837
user4362837

Reputation: 87

C++ custom allocator

Hi I have written a custom allocator with the help of some resources. It works fine for std::vector, list . However for std::unordered_map the constructor gets called twice . I am not why. Can someone please help me understand the static initialization that is happening. Here's the code

File:helper.h

template<typename T>
class helper
{
 static const size_t init_size = 12; // 0xF4240 max number of entries in the data structure
public:
      helper() :
      alloc_size(
      sizeof(link) > sizeof(T) ?
      init_size * sizeof(link) : init_size * sizeof(T)), offset(
      sizeof(link) > sizeof(T) ? sizeof(link) : sizeof(T))
  {
       std::cout <<"Initial allocation done" << " I value : " << i << std::endl;
   }


};

File: main.cpp

int main()
{
    std::unordered_map<long,long,hash<long>, equal_to<long> , myallocator<pair<const long,long> > >            my_map;
}

calling it that way makes the helper constrcutor get called twiced in the program. It doesn'y happen like that for vector. Is there something i am not understanding with regards to template initialization. Please help

Upvotes: 1

Views: 380

Answers (1)

Anton Savin
Anton Savin

Reputation: 41301

Containers may create allocators not only for the type you provided, but also for different types via rebind. This is what apparently happens in your case. You didn't provide enough code so others can compile and check it, but you can add this in the constructor of helper:

std::cout << __PRETTY_FUNCTION__ << std::endl;

This works in GCC and Clang and will show the template parameters the function/class was instantiated with.

Upvotes: 2

Related Questions