开发者

C++ Array of objects at two times

I have a class Agent, which contains a pointer (array) of class ValueContainer.

Now what I have to do is to create an array of Agent first, and then initialize each one of them independently. Also, Agent has no empty constructor due to its nature.

It'开发者_如何学Gos more or less like this:

Agent agent[n];
for (int i...)
{
    load values from hd;
    create a ValueContainer with this values;
    initialize Agent[i] with loaded values;
    deallocate the upstated ValueContainer;
}
// agent's constructor copies the VC values in his own VC,
// so there is no problem of pointers

Unfortunately, I keep on running in segmentation fault errors. I tried allocating the array with malloc, with the upstated declaration, making it an array of pointers. Still, I don't have any results.


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 Agents within this buffer:

new (&buf[byte_index]) Agent(parameter_list);

This is tricky. You have to juggle several things when using placement new:

  1. You need to make sure you use the right byte_index within the buffer.
  2. You need to make sure you deallocate in the correct order: destroy the Agents first, then destroy the buffer they are in.
  3. You have to explicitly call the destructor in order to destroy the Agents:

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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜