删除动态数组? [英] Deleting dynamic arrays?

查看:277
本文介绍了删除动态数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有关于我的项目中删除动态数组的问题。

I'm having problems about deleting dynamic arrays in my project.

第一次出现:

void StudentReviewSystem::addCourse( const int courseId, const string courseName )
{
    int i = findCourse( courseId );

    if ( i == -1 )
    {
        int newNum = numberOfCourses + 1;
        Course *newCourses = new Course[newNum];
        for ( int j = 0; j < numberOfCourses; j++ )
        {
            newCourses[j] = courses[j];
        }
        Course aCourse(courseId, courseName);
        newCourses[numberOfCourses] = aCourse;
        //delete[] courses;
        courses = newCourses;
        numberOfCourses = newNum;
        cout<< "Course "<< courseId <<" has been added."<< endl;
    }
    else
    {
        cout<< "Course "<< courseId <<" has already exist."<< endl;
    }
}

课程是在我的头中定义一个指针。
如果我注释掉删除行,code的作品就好,否则,程序崩溃。

courses is a pointer which was defined in my header. If I comment out the delete line, code works just fine, otherwise, program crashes.

另一个显示:

StudentReviewSystem::StudentReviewSystem()
{
    numberOfCourses = 0;
    courses = new Course[0];
}

StudentReviewSystem::~StudentReviewSystem()
{
    //delete[] courses;
}

我知道我必须删除我的动态数组以避免内存泄漏,但每当我的析构函数被调用,程序崩溃,所以我注释掉该行也。

I know I must delete my dynamic arrays to avoid memory leaks, but whenever my destructor is called, program crashes so I comment out that line too.

每当我尝试删除一个动态数组,程序崩溃,无论我做什么。

Whenever I try to delete a dynamic array, program crashes no matter what I do.

原来,你不是能删除[] 与大小为0阵列所以,我想每一次检查大小删除的数组。但是做了0大小的数组导致内存泄漏?

It turned out that you can't delete[] an array with size 0. So, I check for size every time I want to delete an array. But does a 0 size array causes memory leak?

推荐答案

如果您的类管理资源,那么你通常需要析构函数,拷贝构造函数和拷贝赋值运算符,每的 /stackoverflow.com/questions/4172722\">Rule。我的猜测是,你没有这些,所以班里有无效的复制语义:复制将刚才复制的指针,而不是动态数组,留下两个对象都想要删除同一阵列

If your class manages resources, then you usually need a destructor, copy-constructor, and copy-assignment operator, per the Rule of Three. My guess is that you don't have these, so the class has invalid copy semantics: copying it will just copy the pointer, not the dynamic array, leaving two objects both wanting to delete the same array.

无论是执行或删除复印功能,或者更好,是不管理的资源自己:使用的std ::矢量&lt;场&GT; 做的工作您。您不需要析构函数或者如果你这样做,而 addCourse 就会简单得多。

Either implement or delete the copy functions, or (better still) don't manage the resources yourself: use std::vector<Course> to do the work for you. You won't need the destructor either if you do that, and addCourse would be much simpler.

这篇关于删除动态数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆