2

我正在尝试使用自定义容器,并在该容器的构造函数中传递了一个内存池分配器。整个事情是这样开始的:

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: 'Containers::BList::BList(Allocators::IAllocator &)' : 无法将参数 1 从 'Allocators::IAllocator *' 转换为 'Allocators::IAllocator &' c:\licenta\licenta-transfer_ro -02may-430722\licenta\framework\framework\iallocator.h 21 框架

我想我用这个过头了....

4

3 回答 3

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 &'

那么,你如何从你拥有的指针转换为构造函数想要的引用呢?


好的,我也添加了实际答案:

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);
于 2012-05-02T13:19:21.237 回答
1

您似乎make_new使用指针而不是引用进行调用。尝试:

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

请选择一个压痕阶梯并坚持下去。

于 2012-05-02T13:08:02.500 回答
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); 
于 2012-05-02T13:08:43.670 回答