c++ - Fixed Allocator with stack - how to implement allocate and deallocate? -
i've started code fixedallocator class allocates memory chunks of fixed size , works stack, works in constant time allocate/deallocate. actually, i'll need class use std::vector, have implement std::allocator methods.
everything here learning purposes - don't need complete implementations or headers - real ones have lot of code on problem.
and got stuck on allocate/deallocate methods - understand should somehow reserve memory pool - example using vector, understand should use static_cast convert char type t-type, don't understand how rebuild 2 ideas list. deallocate takes pointer argument, not tnode - that's maybe main problem.
if wrote kind of allocator - answer code perfect. suggestions, links , other source of knowledge welcome. thank you.
here skeleton of code:
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(); } };
Comments
Post a Comment