如何调整动态分配的多态对象数组?

时间:2012-11-21 18:46:01

标签: c++ arrays dynamic polymorphism dynamic-memory-allocation

我有一个动态分配的多态对象数组,我想在不使用STL库(向量等)的情况下调整大小。我已经尝试将原件移动到临时阵列,然后删除原件,然后将原件设置为临时,如下所示:

int x = 100;
int y = 150;

Animal **orig = new Animal*[x];
Animal **temp = new Animal*[y];

//allocate orig array
for(int n = 0; n < x; n++)
{
    orig[n] = new Cat();
}

//save to temp
for(int n = 0; n < x; n++)
{
    temp[n] = orig[n];
}

//delete orig array
for(int n = 0; n < x; n++)
{
    delete orig[n];
}
delete[] orig;

//store temp into orig
orig = temp;

但是,当我尝试访问该元素时,例如:

cout << orig[0]->getName();

我得到了一个糟糕的记忆分配错误:

Unhandled exception at at 0x768F4B32 in file.exe: Microsoft C++ exception: std::bad_alloc at memory location 0x0033E598.

2 个答案:

答案 0 :(得分:4)

//delete orig array
for(int n = 0; n < x; n++)
{
    delete orig[n];
}

对于这种特殊情况,不要这样做。您实际上是删除不是数组的对象。因此,临时数组中的所有对象都指向无效位置。只需执行delete [] orig即可解除分配原始数组。

答案 1 :(得分:1)

你复制错了。而不是复制临时数组只是指向与orig相同的位置。现在当你删除orig时,临时指针指向一个无效的位置。

//save to temp
for(int n = 0; n < x; n++)
{
    //temp[n] = orig[n];
    // Try this instead
    strcpy(temp[n], orig[n]);
}