Re: design problem...
aaragon wrote:
Ulrich Eckhardt wrote:
aaragon wrote:
Funnily, I just did something similar. I implemented a string type that
either has a constant maximal size or a variable size with 8/16/32 bit
size_type. There also was one baseclass that only did the allocation, it
had roughly this interface:
struct allocator: noncopyable
{
allocator();
~allocator();
void alloc( size_t);
char* data();
char const* data() const;
};
It performed size checking in alloc() and managed either a dynamic array
or had a static array. This was used as a policy and everything else was
implemented on top of it. These also can't be static, because internally
it does have data to work with so it needs an object.
This looks nice. How do you give the option between static and dynamic
storage in this policy?
I used two allocator classes, both of which export the above described
interface (plus the capacity() function which I forgot above):
struct dynamic_allocator: noncopyable
{
dynamic_allocator(): m_data(0), m_count(0) { alloc(0); }
~dynamic_allocator() { delete [] m_data; }
void alloc( size_t c)
{
char* new_data = new char[c+1];
delete [] m_data;
m_data = new_data;
m_count = c;
std::fill( m_data, m_data+m_count+1, '\0');
}
size_t capacity() const
{ return m_count; }
char* data()
{ return m_data; }
char const* data() const
{ return m_data; }
private:
char* m_data;
size_t m_count;
};
template<size_t count>
struct fixed_allocator: noncopyable
{
fixed_allocator(): m_data(0), m_count(0) { alloc(0); }
~fixed_allocator() {}
void alloc( size_t c)
{
if(c > count)
throw range_error();
std::fill( m_data, m_data+count+1, '\0');
}
size_t capacity() const
{ return count; }
char* data()
{ return m_data; }
char const* data() const
{ return m_data; }
private:
char m_data[count+1];
};
Uli
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]