使用new调整数组大小

时间:2019-10-12 02:08:17

标签: c++ pointers new-operator

因此,我试图通过使函数调用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;

}

2 个答案:

答案 0 :(得分:0)

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

答案 1 :(得分:0)

关于处理资源, 确保您需要在析构函数中进行重新分配,以在容器类释放资源 被摧毁。当您要调整包含的数组的大小时,可以在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;
        }
    }

您的析构函数很好。

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