0

我有一个动态分配的多态对象数组,我想在不使用 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.
4

2 回答 2

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

对于这种特殊情况,不要这样做。您实际上是在删除对象而不是数组。所以临时数组中的所有对象都指向无效位置。只需delete [] orig释放原始数组即可。

于 2012-11-21T18:49:50.697 回答
1

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

//save to temp
for(int n = 0; n < x; n++)
{
    //temp[n] = orig[n];
    // Try this instead
    strcpy(temp[n], orig[n]);
}
于 2012-11-21T18:55:40.893 回答