它看起来像std :: list的gcc实现。在这种情况下,上下文是:
struct _List_impl : public _Node_Alloc_type { ... };
_List_impl _M_impl;
你忘了写成员函数的返回类型:
typedef _Alloc allocator_type;
allocator_type
get_allocator() const
{ return allocator_type(*static_cast<const _Node_Alloc_type*>(&this->_M_impl)); }
答:(1)
当添加节点在_Tp
类型的列表中,真正需要分配的不是对象_Tp
,而是包含_Tp
(a _List_node<_Tp>
)的列表节点。
所以std :: list需要能够分配一个_List_node<_Tp>
,但它已经为_Tp
提供了一个分配器。这就是模板typedef rebind派上用场的地方:它可以从类型T的分配器获得类型U的分配器。
使用此重新绑定,我们从_Alloc<_Tp>
类型获得_Alloc<_List_node<_Tp> >
。
源文件为注释(2)中的答案:
// NOTA BENE
// The stored instance is not actually of "allocator_type"'s
// type. Instead we rebind the type to
// Allocator<List_node<Tp>>, which according to [20.1.5]/4
// should probably be the same. List_node<Tp> is not the same
// size as Tp (it's two pointers larger), and specializations on
// Tp may go unused because List_node<Tp> is being bound
// instead.
//
// We put this to the test in the constructors and in
// get_allocator, where we use conversions between
// allocator_type and _Node_Alloc_type. The conversion is
// required by table 32 in [20.1.5].
假设_Alloc
的类型是一样的_Node_Alloc_type
按C++标准;因此static_cast声明转换是合法的。
你应该说明你在看什么特定的STL实现。虽然STL接口是标准化的,但实施方式因供应商而异。 – 2009-10-12 19:27:43