可能是重复问题:
什么是三大法则?
我在下面的程序中遇到了内存双重释放的问题。
调试器显示问题出现在push_back()
函数中。
A类:
class A {
public:
A(int x);
int x;
};
A::A(int x) {
this->x = x;
}
二级地址:
class B {
public:
B(int x);
~B();
A* a;
};
B::B(int x) {
this->a = new A(x);
}
B::~B() {
delete a;
}
主要功能:
int main() {
vector<B> vec;
for(int i = 0; i < 10; i++) {
vec.push_back(B(i)); <------------ Issue is here
}
cout << "adding complete" << endl;
for(int i = 0; i < 10; i++) {
cout << "x = " << (vec[i].a)->x << endl;
}
return 0;
}
这段代码有什么问题?
编辑:错误“double free or memory corruption”