在下面的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;
}
在Pair::Pair(const Pair&obj)中,实际上复制了指针,它是双倍析构的。您希望复制指针的内容(请参阅pair::pair(int p1,int p2)构造函数)。
问题是,您的复制构造函数将另一个对象的p1
和p2
分配给了当前对象(q
持有与p
相同的p1
和p2
)。因此在程序结束时,q
的析构函数和p
的析构函数尝试删除两个相同的指针。
在复制构造函数中,应该复制整数,而不是只复制指针。