Protoman wrote:
Is this a good method of repersenting an allocator?:
template <class T, long long X>
class Allocator
{
public:
Allocator(){}
T* allocate()
{
static long long i=0;
T* j=new(&pool[i]) T;
i++;
if(i>X)throw bad_alloc();
else return &*j;
}
private:
static T pool[X];
};
template<class T,long long X> T Allocator<T,X>::pool[X];
Any suggestions? Thanks!!!
There's a couple of issues I have.
1) An allocator is meant to allocate bytes not objects. The memory
returned by your allocator is a fully constructed object which will then
be constructed again when when the memory is returned to the program. So
you will end up with doubly constructed objects. Instead you should do
something like this
class Allocator
{
public:
T* allocate()
{
static long long i=0;
T* j = (T*)&pool[i*sizeof(T)]
i++;
return j;
}
private:
static char pool[X*sizeof(T)];
};
Because pool is an array of char, there is construction of objects
happening.
2) You need to implement a lot more members and types for your code to
be considered a complete allocator.
3) I didn't understand the purpose of
else return &*j;
why not
else return j;
john