By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
454,505 Members | 1,761 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 454,505 IT Pros & Developers. It's quick & easy.

Is this a good method of repersenting an allocator?

P: n/a
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!!!

Nov 22 '05 #1
Share this Question
Share on Google+
2 Replies


P: n/a
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
Nov 22 '05 #2

P: n/a
> 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
Nov 22 '05 #3

This discussion thread is closed

Replies have been disabled for this discussion.