由于缺少析构函数,我最近有一些错误(bad_alloc)。C++析构函数,动态分配
我现在有两个班,这样设置:
class ObjOne {
friend class ObjTwo;
public: //constructors and some other random methods
ObjOne(int n) {
}
ObjOne() {
}
private:
int currSize;
int size;
int *jon;
};
class ObjTwo {
public: //constructors and some other methods
ObjTwo(ObjOne, int n) {} //
ObjTwo() {}
ObjTwo(const ObjTwo &source) { //copy constructor
num = source.num;
x = source.x;
myObjOne=source.myObjOne;
}
~ObjTwo() { //destructor
delete #
delete &x;
delete &myObjOne;
}
private:
ObjOne myObjOne;
int num, x;
};
,这里是我的运营商=为ObjTwo
ObjTwo& ObjTwo::operator=(const ObjTwo& other) {
num = source.num;
x = source.x;
myObjOne=source.myObjOne;
return *this;
}
首先,我的假设是(请更正这些如果是不正确):
ObjOne不需要析构函数,因为它只是基本类型,并且编译器将使用默认析构函数清理它。 ObjTwo需要析构函数,因为它包含ObjOne ObjTwo析构函数将需要从x,num和myObjOne中释放内存。我已经尝试了使用这个析构函数,但是我仍然遇到bad_alloc错误(当测试巨大的循环等)或其他错误(当前它只是当析构函数被调用时崩溃)。
什么我做错了认识任何指导
编辑: 我有一个bad_alloc异常时,我只是把这个在一个循环中被抛出:
ObjTwo b(//some parameters);
ObjTwo a(//some parameters);
for (int i=0; i<20000000; i+) {
bool x = (a == b);
}
,这是重载==运营商
bool ObjTwo::operator==(const ObjTwo& other) {
ObjTwo temp = other;
for(int i=myObjOne.x; i>=0; i--) {
if(myObjOne.get(i)!=temp.myObjOne.get(i)) {
return false;
}
}
return true;
}
经过对错误的一些阅读后,似乎它是由于内存不足造成的;这是我的无能的析构函数会导致的。这里可能是什么问题?
get方法只返回jon [i];
你没有'new'任何东西,没有必要'delete'。 –
你的例子都不正确。你似乎有一些误解。如果你的类分配了一些内存,你需要一个析构函数。 ObjTwo不会这样做,也不需要析构函数。 ObjOne也没有提供给我们的代码。但是ObjOne中的大红旗是指针。如果ObjOne分配一些内存并使用'jon'指向这个内存,那么它确实需要一个析构函数。你应该寻找什么,如果你的类包含指针,那么他们可能需要一个析构函数。 – john
编辑完成后 - 错误可能是因为您的内存不足。但是你还没有向我们展示任何分配内存的代码。到目前为止,你向我们展示的只是糟糕的析构函数。发布完整的代码。 – john