Why do compilers allow an allocator of a different value type than the container used

Viewed 1043

It seems that the C++ STL container requirements are that the provided allocator type's value_type be the same as the STL container's value_type

Requires:allocator_- type::value_type is the same as X::value_type.

However, the following code that uses a vector of strings but with an allocator for doubles works just fine on VS 2012 and g++ 4.4.7. On g++, valgrind does not produce any errors either.

int main()
{
  typedef vector<std::string, std::allocator<double> > StringList;
  StringList s;
  for(int i=0; i < 100; i++){
    stringstream ss;
    ss << i;
    s.push_back(ss.str());
  }
  for(StringList::iterator it = s.begin(); it != s.end(); ++it)
    {
      cout << *it << " ";
    }
  cout << endl;

  return 0;
}

I'm assuming the allocator is being rebound internally to an allocator of the value_type of the container (though maybe I'm wrong).

My question is am I misreading the C++ spec and in fact all containers will always "rebind" the allocator provided to use the type they want? Or is that just a common practice but not guaranteed.

Essentially can I count on this "feature" that containers will always take whatever allocator I provide (of any type) and make it work for the value_type of that container?

2 Answers
Related