[英]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.