Saying that you want to create an array of Agent
without initializing those agents is an anachronism. Initialization takes place during construction. You can't create a thing without doing some kind of initialization.
In almost every case, the "right" thing to do in C++ is to use a vector
or some other Standard container for your array, and then push_back
new elements as you create them. You should see if this is the right approach for you. Without knowing anything at all about your application, it probably is.
Maybe what you mean (or maybe what you want) is to create memory space for the array, and then initialize them as you load them. This is quite rare, but it does happen. In that case, first you can allocate a char
buffer that is big enough to hold all your items:
char buf[correct_size];
...and then use placement-new to initialize your Agent
s within this buffer:
new (&buf[byte_index]) Agent(parameter_list);
This is tricky. You have to juggle several things when using placement new:
- You need to make sure you use the right
byte_index
within the buffer.
- You need to make sure you deallocate in the correct order: destroy the
Agent
s first, then destroy the buffer they are in.
- You have to explicitly call the destructor in order to destroy the
Agent
s:
Example of #3:
Agent* agent = reinterpret_cast<Agent*>(&buf[byte_index]);
agent->~Agent();
This is risky code in about a million different ways. I can't stress strongly enough how no matter how space-age and tempting it may be to try to do this, you probably should not do it in production code. Using placement new should be a last resort when absolutely nothing else will work.