它看起來像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