c++析构函数取消分配失败



在下面的c++代码中,在析构函数调用过程中,它因以下错误而崩溃。

如果打印出这条消息,至少程序还没有崩溃!但您可能还需要打印其他诊断消息。DSCode(16782,0x1000efe00(malloc:***对象0x10742e2f0错误:未分配释放的指针DSCode(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;
}

在您的Pair::Pair(const Pair&obj(中,您实际上复制了指针,该指针后来被双重销毁。您想要复制指针的内容(请参阅Pair::Pair(int p1,int p2(构造函数(。

问题是复制构造函数将另一个对象的p1p2分配给当前对象(qp具有相同的p1p2(。因此,在程序的最后,q的析构函数和p的析构因子试图删除两个相同的指针。

在复制构造函数中,应该复制整数,而不是只复制指针。

相关内容

最新更新