2012-05-02 36 views
2

我試着使用自定義容器,並在該容器的構造函數中傳遞一個內存池分配器。 整個事情開始是這樣的:使用模板容器的構造函數有問題C++

AllocatorFactory alloc_fac; 

//Creates a CPool allocator instance with the size of the Object class 
IAllocator* object_alloc = alloc_fac.GetAllocator<CPool>(1000,sizeof(Object)); 
//Creates a CPool allocator instance with the size of the BList<Object> class 
IAllocator* list_alloc = alloc_fac.GetAllocator<CPool>(10,sizeof(BList<Object>)); 
//Same logic in here as well 
IAllocator* node_alloc = alloc_fac.GetAllocator<CPool>(1000,sizeof(BListNode<Object>)); 

的IAllocator類看起來是這樣的:

class IAllocator 
{ 

public: 

    virtual void* allocate(size_t bytes) = 0; 
    virtual void deallocate(void* ptr) = 0; 

    template <typename T> 
    T* make_new() 
    { return new (allocate(sizeof(T))) T(); } 

    template <typename T, typename Arg0> 
    T* make_new(Arg0& arg0) 
    { return new (allocate(sizeof(T))) T (arg0); } 

      ....... 
} 

和容器類的構造函數是這樣的:

template <class T> 
class BList { 
...... 
public: 
/** 
*@brief Constructor 
*/ 
BList(Allocators::IAllocator& alloc){ 
    _alloc = alloc; 
    reset(); 
    } 
/** 
*@brief Constructor 
*@param inOther the original list 
*/ 
BList(const BList<T>& inOther){ 
    reset(); 
    append(inOther); 
    } 
..... 
} 

當我這樣做:

BList<Object> *list = list_alloc->make_new<BList<Object>>(node_alloc); 

編譯器抱怨這一點:

錯誤1錯誤C2664: '集裝箱:: BList :: BList(分配器:: IAllocator &)':無法從 '分配器:: IAllocator *' 來轉換參數1'分配器:: IAllocator &「C:\ licenta \ licenta-transfer_ro-02may-430722 \ licenta \框架\框架\ iallocator.h 21框架

我覺得我去了我的頭,這一個....

回答

3

現有的答案是正確的,但對如何給自己讀取錯誤的一個小提醒:你只要將其分割成塊......

Error 1 error C2664: 'Containers::BList::BList(Allocators::IAllocator &)' : cannot convert parameter 1 from 'Allocators::IAllocator *' to 'Allocators::IAllocator &' 

寫着:

  • 你叫Containers::BList::BList(Allocators::IAllocator &),這是一個構造函數採取一個參數,對IAllocator的引用
  • cannot convert parameter 1意味着編譯器具有
    • 你給它這種類型的第一個(也是唯一一個)參數的類型麻煩:... from 'Allocators::IAllocator *'
    • ,並希望這種類型的(相匹配的構造函數聲明):... to 'Allocators::IAllocator &'

那麼,你如何從指針轉換爲你需要的構造函數?


OK,我已經添加了實際的答案,以及:

Allocators::IAllocator *node_alloc = // ... 
Allocators::IAllocator &node_alloc_ref = *node_alloc; 
BList<Object> *list = list_alloc->make_new<BList<Object>>(node_alloc_ref); 

或者只是:

BList<Object> *list = list_alloc->make_new<BList<Object>>(*node_alloc); 
+0

+1解釋的錯誤消息。 –

+0

感謝您的所有答案。它們都是有效的,但是因爲我只能將其中一個標記爲解決方案,所以我選擇它是因爲它具有較高的教育價值:p。 –

1

您似乎打電話make_new與一個點而不是參考。請嘗試:

BList<Object> *list = list_alloc->make_new<BList<Object>>(*node_alloc); 

而且,請選擇一個壓痕階梯並堅持下去。

0

您的分配器工廠正在返回一個指向分配器的指針,但您的構造函數需要對分配器的引用。您需要取消引用指針。

IAllocator* node_alloc = alloc_fac.GetAllocator<CPool>(1000,sizeof(BListNode<Object>));  

// Instead of: 
// BList<Object> mylist(node_alloc); 
// you need: 
// 
BList<Object> mylist(*node_alloc);