【问题标题】:Trouble with destructor in overloaded = STATUS_ACCESS_VIOLATION重载中的析构函数问题= STATUS_ACCESS_VIOLATION
【发布时间】:2013-04-06 09:02:08
【问题描述】:

我需要重载= 才能对我的班级实例进行深度复制。 在我尝试将大量随机数据设置为输入之前,它工作得很好。然后我收到这条消息:

异常:在 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,因为我不允许使用它们。我敢肯定,重载= 的函数会成功结束,并且在尝试完成分配时会打印出此错误消息。

如果有人可以告诉我,析构函数应该是什么样子,我会很高兴,因为我已经尝试解决这个问题几个小时但没有任何成功:(

【问题讨论】:

    标签: c++ pointers memory-management destructor


    【解决方案1】:

    您不需要在 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;
    }
    

    【讨论】:

      猜你喜欢
      • 2020-12-17
      • 2020-07-13
      • 1970-01-01
      • 1970-01-01
      • 2010-10-28
      • 2014-06-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多