Pre-Allocate a General Class Instance

P

pandy.song

In my project, there is a class "Father",
from which lots of "CHILD" class are inherited.

For the system is real-time embedded system,
"new" operation is applied here.

I want to pre-allocate a series of general
"CHILD" instances. Every time I want a specified
"CHILD" , I get one from a link list.

In C++, virtual class "FATHER" can not be
instanced.So the method I can bring to my mind
is to instance each "CHILD" class, and every
time I want a specified "CHILD", I get a memory
From a link list, and "memcpy" it.

This "memcpy" copy not only internal data ,but
virtual funtion table.

The method I memtion above may not be clever method.

I wander if there are better methods.

Thank you for your readimg this thread.
 
T

tom_usenet

In my project, there is a class "Father",
from which lots of "CHILD" class are inherited.

For the system is real-time embedded system,
"new" operation is applied here.

I want to pre-allocate a series of general
"CHILD" instances. Every time I want a specified
"CHILD" , I get one from a link list.

In C++, virtual class "FATHER" can not be
instanced.So the method I can bring to my mind
is to instance each "CHILD" class, and every
time I want a specified "CHILD", I get a memory
From a link list, and "memcpy" it.

This "memcpy" copy not only internal data ,but
virtual funtion table.

You can't safely memcpy objects of non-POD type. Depending on the
implementation (and presense of e.g. virtual inheritence) it may not
work. This ignores the possible problems of double deletion, etc.
The method I memtion above may not be clever method.

I wander if there are better methods.

Use placement new. E.g. to get a new CHILD1 object, do this:

void* mem = obtain_memory_from_pool(sizeof(CHILD1));
CHILD1* child1 = new (mem) CHILD1(params);

//to delete:
child1->~CHILD1(); //(or as a Father*)
return_memory_to_pool(child1);


Or, alternatively, provide new/delete in Father. e.g.

class Father
{
public:
virtual ~Father();
//etc.

void* operator new(size_t amount)
{
//return "amount" of memory from linked list
}

void* operator delete(void* ptr, size_t amount)
{
//return memory to linked list.
}
};

Finally, check out boost's pool library:
http://www.boost.org/libs/pool/doc/index.html

Tom

C++ FAQ: http://www.parashift.com/c++-faq-lite/
C FAQ: http://www.eskimo.com/~scs/C-faq/top.html
 

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
474,156
Messages
2,570,878
Members
47,404
Latest member
PerryRutt

Latest Threads

Top