[英]How to resize a dynamically allocated array of polymorphic objects?
我有一个动态分配的多态对象数组,我想在不使用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.
//delete orig array
for(int n = 0; n < x; n++)
{
delete orig[n];
}
对于这种特殊情况, 请不要执行此操作 。 您实际上是在删除对象而不是数组。 因此,临时数组中的所有对象都指向无效位置。 只需执行delete [] orig
即可取消分配原始数组。
您复制错误。 无需复制临时数组,只需指向与原始位置相同的位置即可。 现在,当您删除原件时,临时指针将指向无效的位置。
//save to temp
for(int n = 0; n < x; n++)
{
//temp[n] = orig[n];
// Try this instead
strcpy(temp[n], orig[n]);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.