我试图为std::vector<char>
使用自定义分配器,但我注意到std::vector
不需要/使用我的分配器中的任何成员函数。这怎么可能?std :: vector <char>的自定义分配器被忽略
#include <vector>
struct A : private std::allocator<char> {
typedef std::allocator<char> alloc;
using alloc::value_type;
using alloc::pointer;
using alloc::const_pointer;
using alloc::difference_type;
using alloc::size_type;
using alloc::rebind;
// member functions have been removed, since the program compiles without them
};
int main() {
std::vector<char, A> v;
v.resize(4000);
for (auto& c : v)
if (c)
return 1; // never happens in my environment
return 0; // all elements initialized to 0. How is this possible?
}
我正在尝试使用在线C++ 11编译器(LiveWorkSpace)提供g ++ 4.7.2,4.8和4.6.3的上述程序。
基本上allocate()
,deallocate()
,construct()
和destroy()
未在我的分配器限定,然而程序编译,所有的元件将被初始化为0。
实际上,为什么如果用户提供'std :: allocator'作为'vector '的分配器,它仍然可以工作?得到编译器错误是否更有意义? –
2013-03-05 13:40:01
我不确定这是否令人满意,但始终如此。对于其他容器,它更有意义:如果用户说'std :: map,std :: allocator >>'尽管可以接受它从技术上来说,分配器必须是'std :: allocator >' –
2013-03-05 13:42:56
@AndyProwl - 分配器实际上应该是模板模板参数,但模板模板参数在当时不存在STL(注意:** STL **,不是**标准库**)被设计,所以'rebind'被创建。 – 2013-03-05 13:48:54