使用新的调整数组大小
Resize array using new
所以我试图通过调用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;
}
}
您的析构函数很好。
您的代码可能会有进一步的改进,但这与您的问题有关。
相关文章:
- 为char数组调整zlib-zpipe
- 当您在此单词中搜索单词时调整字符数组的大小?
- 调整大小和复制哈希表数组中的元素
- 尝试将数组大小调整为 -1
- 将动态分配的数组的大小调整为较小的大小C++
- 我的C++程序有问题.涉及动态调整整数数组的大小
- 通过新的后传递后创建的动态数组的错误以调整函数
- 在哈希表中调整字符串数组的大小
- 与教科书上关于未调整大小的数组初始化C++句子的混淆
- 调整双指针数组C++大小
- 调整结构/字符数组的大小(以减少内存使用)
- 我的数组大小调整代码在新数据上引发异常[size_t]
- 如何使用3D char数组调整双指针2D char阵列的大小
- C++ 数组将所有值调整相同的量
- 调整动态数组大小时保留用户输入的值的问题
- C++我需要能够调整动态数组的大小
- 如何调整属于类的唯一指针的字符数组的大小.它必须在程序的整个生命周期中保持活力
- 调整小于连续数组的 C++ 矢量大小
- 我需要调整指针数组的大小
- 动态数组调整大小函数问题