c++ - 测试对象是否被删除

标签 c++ object testing delete-operator

请看下面的代码:

class Node
{
private:
    double x, y;
public:
    Node (double xx, double yy): x(xx), y(yy){}
};

int main()
{
  Node *n1 = new Node(1,1);
  Node *n2 = n1;

  delete n2; 
  n2 = NULL;

  if (n1 != NULL) //Bad test
  {
     delete n1;   //throw an exception
  }
}

有两个指针n1、n2指向同一个对象。我想使用 n1 指针测试来检测 n2 是否被删除。但是这个测试结果异常。

有什么方法可以使用 n1 指针来确定对象是否被删除(或未被删除)?

最佳答案

据我所知,处理这种情况的典型方法是使用引用计数指针,就像(例如)COM 所做的那样。在 Boost 中,有一个 shared_ptr 模板类可以提供帮助(http://www.boost.org/doc/libs/1_42_0/libs/smart_ptr/shared_ptr.htm)。

关于c++ - 测试对象是否被删除,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2758014/

相关文章:

asp.net - 将 ASP.NET 转发器与数组一起使用?

c++ - 优先规则

c++ - 将char数组传递给exec *()系列函数后,如何释放它们的内存

c++ - 实现观察者模式 C++

javascript - 等同于 rspec =~ 对于 Chai 中的数组

c++ - py.test 与非 python 测试(具体来说,与 cxxtest)

c++ - 将一个类声明为静态的?

Javascript:从已经实例化的对象与原型(prototype)创建对象

java - 在构造函数中传递接口(interface)对象作为参数

c# - 为什么 object.ToString() 存在?