c++ - 重载中的析构函数出现问题 = STATUS_ACCESS_VIOLATION

标签 c++ pointers memory-management destructor

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

Exception: STATUS_ACCESS_VIOLATION at eip=004042F3 and then it prints out the stack..

我假设,我需要在复制之前删除数组中的值,但我无法弄清楚它应该是什么样子。 我试过这个:

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

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

最佳答案

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

关于c++ - 重载中的析构函数出现问题 = STATUS_ACCESS_VIOLATION,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15995004/

相关文章:

c++ - 如何调用一个函数,该函数的参数是指向结构指针数组的指针和未指定的大小

c++ - 如何知道指针指向堆还是栈?

c - 在 mcu 上的 malloc 之后需要一个 free()(即使数组/指针总是在使用中)?

c++ - 使用 Visual C++ 构建时如何使用 SSE(以及 SSE2、SSE3 等)扩展?

c - 指向结构的指针数组中的指针,如果设置为 NULL,是否分配内存?

c# - C++/CLI 项目如何引用可移植类库?

c++ - 构建一个 char* vector

javascript - 对象引用会占用额外的内存吗?

c++ - 如何在另一个终端中从 C++ 打开和稍后关闭另一个程序?

c++ - 对 `vtable for DigitalClock' 的 undefined reference - 对 `DigitalClock::staticMetaObject' 的 undefined reference - Qt