对指针调用delete之后要记得把指针赋值为nullptr

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了对指针调用delete之后要记得把指针赋值为nullptr相关的知识,希望对你有一定的参考价值。

对指针调用delete之后要记得把指针赋值为nullptr

否则,如果这个指针被重复delete,会死机。

#include <iostream>
using std::cout;
using std::endl;
using std::ostream;

class Tree {
  int height;
public:
  Tree(int treeHeight) : height(treeHeight) {
    cout << __func__ << "(), this = " << this << endl;
  }
  ~Tree() { cout << "~Tree()\n"; }
#if 0 
  friend ostream&
  operator<<(ostream& os, const Tree* t) {
    return os << "Tree height is: "
              << t->height << endl;
  }
#else
  friend ostream&
  operator<<(ostream& os, const Tree& t) {
    return os << "Tree height is: "
              << t.height << endl;
  }
#endif
}; 

int main() {
  Tree* t = new Tree(40);
  delete t;
  //t = nullptr;
  delete t;
}

运行结果:

[email protected]:~/project/test/cpp/new_del$ ./a.out 

Tree(), this = 0x13b2010

~Tree()

~Tree()

*** Error in `./a.out‘: double free or corruption (fasttop): 0x00000000013b2010 ***

Aborted (core dumped)


本文出自 “用C++写诗” 博客,谢绝转载!

以上是关于对指针调用delete之后要记得把指针赋值为nullptr的主要内容,如果未能解决你的问题,请参考以下文章