Is this a good method of repersenting an allocator?

P

Protoman

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) 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!!!
 
J

John Harrison

Protoman said:
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) 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
 
J

John Harrison

Because pool is an array of char, there is construction of objects
happening.

Typo

Because pool is an array of char, there is *no* construction of objects
happening.

john
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,766
Messages
2,569,569
Members
45,042
Latest member
icassiem

Latest Threads

Top