使用新的调整数组大小

Resize array using new

本文关键字:数组 调整      更新时间:2023-10-16

所以我试图通过调用ResizeArray((函数来调整数组的大小。但是,我不知道在这种情况下使用"删除"的正确方法是什么。(我制作一个新的int *并将值从原始值复制到它,然后我使原始指针指向新指针,现在我不知道要"删除"什么

class Base
{
private:
int sizeInClass;
int *arrayy=nullptr;
public:
Base(int s)
{
sizeInClass=s;
arrayy = new int[s]{};
setValue();
};
void setValue()
{
for(int x=0;x<sizeInClass;x++)
{
arrayy[x]=x;
}
}
void print()
{
int countter=0;
for(int x=0;x<sizeInClass;x++)
{
countter++;
cout<<arrayy[x]<<endl;
}
cout<<"The size of the array is : "<<countter<<endl;
}

void ResizeArray(int newSize)
{
int *newArray = nullptr;
newArray = new int[newSize];
for(int x=0;x<sizeInClass;x++)
{
newArray[x]=arrayy[x];
}
delete [] arrayy;    /////////////////////////////////// should i use deleate here ? 
arrayy = newArray;
delete [] newArray; /////////////////////////////////// or should I use deleate here ?
sizeInClass = newSize;
}

~Base()
{
delete [] arrayy;  /////////////////////////////////// or just use delete here
arrayy=nullptr; 
}
};

int main()
{
Base b(5);
b.print();
b.ResizeArray(8);
b.setValue();
b.print();
return 0;
}

建议delete的第一个和第三个是正确的。

关于处理资源, 当然,您需要在析构函数中取消分配,以便在容器类时释放资源 被摧毁了。当您要调整包含数组的大小时,您将在ResizeArray函数中处理它,因此以下是它的基本建议,并附有澄清注释:

void ResizeArray(int newSize)
{
int *newArray = new int[newSize];
if (nullptr != newArray) { // we take action only if allocation was successful
for(int x=0;x<sizeInClass;x++)
{
newArray[x]=arrayy[x];
}
delete [] arrayy;    // good, here you delete/free resources allocate previously for an old array 
arrayy = newArray;   // good, you redirect member ptr to newly allocated memory

/* delete [] newArray; ups, we have member ptr point to this location 
and we cannot delete it, after this, accessing it would be UB, 
beside in dtor we would have double, second deletion */
sizeInClass = newSize;
}
}

您的析构函数很好。

您的代码可能会有进一步的改进,但这与您的问题有关。