重载中的析构函数问题= STATUS_ACCESS_VIOLATION

时间:2013-04-14 02:09:35

标签: c++ pointers memory-management destructor

我需要重载=才能对我的班级实例进行深层复制。 它工作得很好,直到我尝试设置一些随机数据的输入。然后我收到这条消息:

  

例外:在eip = 004042F3处的STATUS_ACCESS_VIOLATION   然后它打印出堆栈..

我认为,我需要在复制之前删除数组中的值,但是我无法弄清楚它是怎么样的。 我试过这个:

  for (int i = 0; i != position-1; i++) {
    for (int j=0;j!=db[i]->position-1;j++)
        delete &db[i]->change[j];
    delete db[i];
}
delete[] db;
db = new DbPerson*[other.size];

,但情况变得更糟,程序甚至更早就以失败告终......

这里是使用过的组件的声明:

int size;
int position;
DbPerson** db;

...

class DbChange {
public:
DbChange();
const char* date;
const char* street;
const char* city;
};

DbChange::DbChange() {
date = "";
street = "";
city = "";
}

class DbPerson {
public:
DbPerson(void);
const char* id;
const char* name;
const char* surname;
DbChange * change;
int position;
int size;
};

DbPerson::DbPerson() {
position = 0;
size = 1;
change = new DbChange[1];
}

当剩余的空间不足时,可以调整所有数组的大小,并保存在position变量中的所有项目的实际计数。请不要建议我使用Vectorstring,因为我不允许使用它们。我确定,重载=的函数已成功结束,并且在尝试完成分配时会打印出此错误消息。

如果有人向我展示,破坏者怎么样,我会很高兴因为,我已经试图解决这个问题好几个小时而没有任何成功:(

1 个答案:

答案 0 :(得分:2)

您不需要在DbPerson的每个对象中预删除 DbChange。你可以在DbPerson中调用DbChange的析构函数。

看看:

class DbChange
{
public:
     const char* id;
     const char* Name;

     DbChange(): id(""), Name("")
     {}

     ~DbChange()
     {
         delete [] id;
         delete [] Name;
     }
 };

class DbPerson
{
 public:
    const char* id;
    const char* name;
    const char* surname;
    DbChange * change;
    int position;
    int size;

    DbPerson(): id(""), name(""), surname(""), position(0), size(1)
    {
        change = new DbChange[1];
    }

    void SHOW(void) const
    {
        cout << "Name:      " << name << endl
             << "Surname:   " << surname << endl
             << "position:  " << position << endl;
    }

    ~DbPerson()
    {
        delete [] change; // Calling Destructor for DbChange
        delete [] id;
        delete [] name;
        delete [] surname;
    }
};

int main()
{
    const int global_size_of_DbPerson = 10;
    DbPerson** db;
    db = new DbPerson* [global_size_of_DbPerson];

    for(int i = 0; i < global_size_of_DbPerson; i++)
    {
        db[i] = new DbPerson [global_size_of_DbPerson];
    }

    for(int i = 0; i < global_size_of_DbPerson; i++)
    {
        delete [] db[i];
    }

    cout << "It Worked\n";
    delete [] db;

    return 0;
}