【问题标题】:c++ Destructor de-allocation failingc ++析构函数解除分配失败
【发布时间】: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-&gt;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


【解决方案1】:

在您的 Pair::Pair(const Pair &obj) 中,您实际上复制了指针,该指针稍后会被双重破坏。您想复制指针的内容(参见 Pair::Pair(int p1, int p2) 构造函数)。

【讨论】:

  • 谢谢,更改复制构造函数如下修复它。Pair::Pair(const Pair &obj) { this->pa= new int(*obj.pa); this->pb = new int(*obj.pb); }
【解决方案2】:

问题在于,您的复制构造函数将另一个对象的p1p2 分配给当前对象(q 拥有与p 相同的p1p2)。所以在程序结束时,q 的析构函数和p 的析构函数尝试删除这两个相同的指针。

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

【讨论】:

    猜你喜欢
    • 2013-12-14
    • 2011-01-21
    • 1970-01-01
    • 2013-03-20
    • 2013-05-23
    • 1970-01-01
    • 2018-11-05
    • 1970-01-01
    • 2023-01-11
    相关资源
    最近更新 更多