修复了具有堆栈的分配器 - 如何实现分配和解除分配?

时间:2014-03-23 18:31:04

标签: c++ memory-management allocator

我已经开始编写FixedAllocator类的代码,它通过固定大小的块分配内存并作为堆栈工作,因此它可以在恒定的时间内分配/解除分配。实际上,我需要这个类与std :: vector一起使用,所以我必须实现所有std :: allocator方法。

这里的所有内容都是出于学习目的,所以 - 我不需要任何完整的实现或标题 - 真正的实现有很多代码来解决我的问题。

我被困在分配/解除分配方法 - 我明白我应该以某种方式保留一些内存池 - 例如使用vector,我明白我应该使用static_cast将char类型转换为T类型,但我不知道完全理解如何将这两个想法重建成列表。 Deallocate将指针作为参数,而不是TNode - 这可能是主要问题。

如果有人已经写过这种分配器 - 用代码回答将是完美的。 欢迎任何建议,链接和其他知识来源。谢谢。

这是代码的骨架:

template <typename T, unsigned int nodeSize> 
class FixedAllocator : public std::allocator<T>{
private:
    static size_t Used;
    static const size_t MAX_SIZE = 100000;

struct TNode {
    TNode* next;
    char data[nodeSize];
};

TNode* head;

public:
typedef T* pointer;
typedef const T* const_pointer;
typedef T & reference;
typedef const T & const_reference;
typedef T value_type;
template <typename U> struct rebind { typedef allocator<U> other; };

FixedAllocator() {
    if (Pool.empty()) {
        Pool.resize(MAX_SIZE * sizeof(T));
        Used = 0;
    }   
}

FixedAllocator(const FixedAllocator &) {
}

template<typename U>
FixedAllocator(const FixedAllocator<U> &) {
    if (Pool.empty()) {
        Pool.resize(MAX_SIZE * sizeof(T));
        Used = 0;
    }
}

pointer address(reference x) const {
    return &x;
}

const_pointer address(const_reference x) const {
    return &x;
}

pointer allocate(size_t n, FixedAllocator<void>::const_pointer = 0) {}

void deallocate(pointer, size_t) {}

size_t max_size() const throw() {
    return MAX_SIZE - size;
}

void construct(pointer p, const_reference val) {
    new (static_cast<void*>(p)) value_type(val);
}

void destroy(pointer p) {
    p->~value_type();
}
};

0 个答案:

没有答案
相关问题