【发布时间】:2021-06-12 00:19:00
【问题描述】:
在下面的 c++ 代码中,在析构函数调用期间,它会因以下错误而崩溃。
如果打印了这条消息,至少程序还没有崩溃! 但是您可能还想打印其他诊断消息。 DSCodes(16782,0x1000efe00) malloc: *** 对象 0x10742e2f0 的错误:未分配指针被释放 DSCodes(16782,0x1000efe00) malloc: *** 在 malloc_error_break 中设置断点进行调试
谁能指出析构函数中的错误
class Pair {
public:
int *pa,*pb;
Pair(int, int);
Pair(const Pair &);
~Pair();
};
Pair::Pair(int p1, int p2)
{
this->pa = new int;
this->pb = new int;
*pa = p1;
*pb = p2;
}
Pair::Pair(const Pair &obj)
{
this->pa= new int;
this->pb = new int;
this->pa = obj.pa;
this->pb = obj.pb;
}
Pair::~Pair()
{
if(pa)
delete (pa);
if(pb)
delete(pb);
}
/* Here is a main() function you can use
* to check your implementation of the
* class Pair member functions.
*/
int main() {
Pair p(15,16);
Pair q(p);
Pair *hp = new Pair(23,42);
delete hp;
std::cout << "If this message is printed,"
<< " at least the program hasn't crashed yet!\n"
<< "But you may want to print other diagnostic messages too." << std::endl;
return 0;
}
【问题讨论】:
-
请提醒自己
ptr = 0和*ptr = 0之间的区别 -
为什么对两个整数使用动态分配?指向 int 的指针至少占用与 int 本身一样多的空间,这还没有内存分配的开销。除非你有很好的理由使用指针,否则
int a, b应该是最好的选择。 -
这并没有解决问题,但是这段代码可以写得更简单。所有那些
this->s 只是噪音;编译器知道成员是什么。并且您可以在分配时进行初始化。所以pa = new int(p1);。而且,真的,它应该在初始化列表中:Pair::Pair(int p1, int p2 : pa(new int(p1), pb(new int(p2) {}。最后,您不需要在删除指针之前测试空指针。所以Pair::~Pair() { delete pa; delete pb; }.
标签: c++ destructor