2012-05-11 63 views
8

std::allocatorconstructdestroy成員函數參數的元素的類型來構造:爲什麼std :: allocator :: construct和std :: allocator :: destroy在元素類型上模板化?

template<class T> 
    class allocator 
{ 
    public: 
    typedef T value_type; 
    typedef T* pointer; 

    template<class U, class... Args> 
     void construct(U *p, Args&&... args); 

    template<class U> 
     void destroy(U *p); 

    ... 
}; 

什麼是這個理?他們爲什麼不採取value_type*pointer?似乎allocator<T>應該只知道如何構建或銷燬T類型的對象。

回答

16

這與allocator需要具有rebind<U> typedef的原因相同:因爲許多容器永遠不會分配T s。

取鏈表。這些分配節點,其中每一個都包含 a T作爲成員。因此allocator需要能夠分配他們不知道的某種類型(通過rebind<U>)。但是,這需要複製操作:它需要創建rebind<U>::other類型的新分配器。

如果可能,最好避免這種情況。因此,對於構建和銷燬,分配器需要對任何類型執行適當的操作,例如鏈接列表的內部節點類型。這也使得鏈表的內部節點類型可以具有Allocator::construct/destruct作爲朋友功能。

相關問題