c++ - 如何调整动态分配的多态对象数组的大小?

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

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

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.

最佳答案

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

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

关于c++ - 如何调整动态分配的多态对象数组的大小?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13500017/

相关文章:

c++ - 顺序和并行版本给出不同的结果 - 为什么?

php - 如何使用数组更新

python - 为什么我们在 Numpy 中进行双 bool 索引会得到这样的结果?

c - 如何将特定大小的二维数组从动态更改为静态?

c# - 如何在 LINQ 中创建动态选择表达式?

c++ - Stack(int = 10),这个语法是什么意思(C++)?

c++ - 在 C++ 中,我如何远程设置注册表项(连接工作正常但设置不起作用!) - 在控制台应用程序中?

c++ - 调试错误。 R6010 abort 已被调用()

arrays - 减少,操纵初始值

JavaScript 为动态按钮和输入创建函数