为什么编译器允许使用与使用的容器不同的值类型的分配器

inn*_*der 6 c++ containers stl allocator

似乎C++ STL容器要求提供的分配器类型的value_type与STL容器的value_type相同

要求:allocator_- type :: value_type与X :: value_type相同.

但是,以下使用字符串向量但带有双精度分配器的代码在VS 2012和g ++ 4.4.7上运行正常.在g ++上,valgrind也不会产生任何错误.

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

我假设分配器正在内部反弹到容器的value_type的分配器(虽然可能我错了).

我的问题是我误读了C++规范,实际上所有容器都会"重新绑定"提供的分配器以使用他们想要的类型吗?或者这只是一种常见的做法,但不能保证.

基本上我可以依靠这个"功能",容器将始终采用我提供的任何分配器(任何类型)并使其适用于该容器的value_type?

Mar*_*low 5

如果您尝试建立与铛/的libc ++(加入相应的代码includesusing namespace std;,你会得到:

/ Sources/LLVM/llvm/projects/libcxx/include/vector:474:5:error:static_assert failed"Allocator :: value_type必须与value_type的类型相同"static_assert((is_same :: value),

无论如何,标准对此非常清楚(在c ++ 11/14/1z中 - 但不是c ++ 03):

*Requires:* `allocator_type::value_type` is the same as `X::value_type`
Run Code Online (Sandbox Code Playgroud)

因此,如果您尝试实例化vector<std::string, std::allocator<double> >,您将获得未定义的行为 - 并且"似乎工作正常"是一个特别繁琐的未定义行为版本.但实际上,它"似乎现在工作正常"