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