2012-05-02 38 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);