【发布时间】:2017-04-01 12:06:54
【问题描述】:
在下面的代码示例中,Visual Studio 给出了错误“堆已损坏”。起初 for 循环似乎工作正常,但经过 1 或 2 次迭代后它就崩溃了。
我觉得我的函数myReAllocate 促进了某种不应该发生的内存泄漏(因为当我将其注释掉时,一切正常)。到底发生了什么?这似乎是一个非常微妙的错误。
#include <iostream>
using namespace std;
class myClass{};
void myReAllocate(myClass* c)
{
delete c;
c = new myClass();
}
int main(void)
{
myClass *cc[10];
for (int i = 0; i < 10; i++){
cout << i << " attempt" << endl;
cc[i] = new myClass();
myReAllocate(cc[i]);
delete cc[i];
}
return 0;
}
我尝试添加operator=,但也没有用。
myClass operator=(myClass& right) {
myClass temp = right;
return *this;
}
【问题讨论】:
标签: c++ operator-overloading heap-memory new-operator delete-operator