【发布时间】:2013-03-20 14:53:32
【问题描述】:
由于缺少析构函数,我最近遇到了一些错误(bad_alloc)。
我目前有两个班,这样设置的:
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指向该内存,那么它肯定需要一个析构函数。这就是你应该寻找的,如果你的类包含指针,那么它们很可能需要一个析构函数。 -
编辑后 - 错误很可能是因为您的内存不足。但是您还没有向我们展示任何分配内存的代码。到目前为止,您向我们展示的只是写得不好的析构函数。发布完整代码。
标签: c++ constructor operator-overloading destructor rule-of-three