1

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

2
  • --1: "the constrcutor"? Which one? Please post a stackoverflow.com/help/mcve -- one that actually compiles. Please include both what output you expect, and what you got, exactly. Have you read the "how to ask a question" help pages? They should walk you through it. Commented Dec 15, 2014 at 15:31
  • thanks for the suggestion. i have made the changes. Commented Dec 15, 2014 at 16:07

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

thanks for the suggetion. I tried putting that in the helper constructor and i get the following . it gets called with with T = std::__detail::_Hash_node_base* and then it gets called with T = std::__detail::_Hash_node<std::pair<const long unsigned int, long unsigned int> . Why does it do that? Thanks

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.