似乎 C++ STL 容器要求提供的分配器类型的 value_type 与 STL 容器的 value_type 相同
要求:分配器_- type::value_type 是一样的 作为 X::value_type。
但是,以下使用字符串 vector 但带有 double 分配器的代码在 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;
}
我假设分配器正在内部反弹到容器的 value_type 的分配器(尽管我可能错了)。
我的问题是我是否误解了 C++ 规范,实际上所有容器总是“重新绑定(bind)”提供的分配器以使用它们想要的类型?或者这只是一种常见的做法但不能保证。
从本质上讲,我能否指望容器将始终采用我提供的(任何类型的)任何分配器并使其适用于该容器的 value_type 的“功能”?
最佳答案
如果您尝试使用 clang/libc++ 构建您的代码(添加适当的 includes
和 using namespace std;
,您将得到:
/Sources/LLVM/llvm/projects/libcxx/include/vector:474:5: error: static_assert failed "Allocator::value_type must be same type as 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`
因此,如果您尝试实例化 vector<std::string, std::allocator<double> >
,你会得到未定义的行为 - 而“似乎工作正常”是未定义行为的一个特别繁重的版本。但实际上,它“目前似乎工作正常”
关于c++ - 为什么编译器允许使用与所用容器不同的值类型的分配器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44104698/