【问题标题】:Pass data to allocator将数据传递给分配器
【发布时间】:2014-01-01 10:22:13
【问题描述】:

我现在开始学习如何编写分配器,我想编写一个使用提供的固定大小内存池的简单分配器。

到目前为止,我有:

template<typename T>
class PtrAllocator : public BasicAllocator<T>
{
    private:
        T* ptr;

    public:
        typedef typename BasicAllocator<T>::pointer pointer;
        typedef typename BasicAllocator<T>::size_type size_type;
        typedef typename BasicAllocator<T>::value_type value_type;

        template<typename U>
        struct rebind {typedef PtrAllocator<U> other;};

        PtrAllocator(T* ptr) : ptr(ptr) {}

        pointer allocate(size_type n, const void* hint = 0) {return static_cast<pointer>(&ptr[0]);}
        void deallocate(void* ptr, size_type n) {}
        size_type max_size() const {return 5000;}
};


int main()
{
    int* ptr = new int[5000];
    std::vector<int, PtrAllocator<int>> v(PtrAllocator<int>(ptr));
    v.reserve(100);

    delete[] ptr;
}

上面给了我以下错误:

request for member 'reserve' in 'v', which is of non-class type 'std::vector<int, PtrAllocator<int> >(PtrAllocator<int>)'

我希望能够以某种方式将我的 ptr 传递给我的分配器,以便 std::vector 使用它。

有什么想法可以做到这一点吗?

编辑:我解决了。我必须为main 使用以下内容:

int main()
{
    int* ptr = new int[5000];
    PtrAllocator<int> alloc = PtrAllocator<int>(ptr); //declared on a separate line :l
    std::vector<int, PtrAllocator<int>> v(alloc);
    v.resize(100);

    delete[] ptr;
}

【问题讨论】:

    标签: c++


    【解决方案1】:

    您不能将在您的情况下是动态的指针作为静态的模板参数传递。如果它是静态的,您可以传递一个指针,例如如果您要使用全局分配的对象。

    您可以做的是将指向pool 的指针作为C++ allocators, specifically passing constructor arguments to objects allocated with boost::interprocess::cached_adaptive_pool 中指出的构造参数传递:

    在 C++0x 中,分配器应该能够调用任何构造函数,而不仅仅是复制构造函数 [...]

    编辑关于您的评论:关键是,分配器分配内存但不初始化它。因此,您只能控制例如内存放置或至少一些基本初始化(设置 0 或其他)。要初始化内存,必须构造一个对象。为此,您可以实现 construct,因为 C++11 接受一系列参数,请参阅 hereherehere。或者您可以使用new/delete 进行构造和分配,如here 指出的那样。

    【讨论】:

    • 并非所有指针都是动态的。您可以将全局变量的地址传递给模板。
    • 是的,但他不想在全球范围内创建他的池。对不起,应该指出更多。进行了编辑。
    • 我编辑了我的帖子。我试过你说的。我不知道如何通过std::vector 构造将任何内容传递给分配器。
    • 我想通了。我接受了你的回答。这不是我想要的,但我将我的发现添加到了 OP。
    猜你喜欢
    • 2019-08-30
    • 1970-01-01
    • 2020-04-09
    • 2011-07-05
    • 1970-01-01
    • 1970-01-01
    • 2021-05-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多