c++ - 检查已删除对象的值

标签 c++

我问了一个问题:

Detecting if an object is still active or it has been destroyed

考虑到我不能使用库,C++ 中没有开箱即用的好的解决方案。因此,通过分析已删除对象所在的内存来检查对象是否已被销毁是一种不好的做法吗,请考虑以下代码:

#include <stdio.h>

class Foo {
 public:
    static unsigned int foo_id_gen;    // unique id generator
    unsigned int id;
    int a;
    Foo() {
      ++foo_id_gen;
      if (foo_id_gen == 0) {           // Handle rollover of unique ID
        ++foo_id_gen;
      }
      id = foo_id_gen;                 // Set unique ID
    }
    ~Foo() {
      id = 0;                          // Set unique ID to Zero
    }
};

unsigned int Foo::foo_id_gen = 0;

class FooPtr {
 public:
    Foo* ptr;
    unsigned int id;
    explicit FooPtr(Foo* foo_obj_ptr) {
      ptr = foo_obj_ptr;
      id = foo_obj_ptr->id;
    }
    bool valid() {
      return (ptr->id == id);
    }
};

int main() {
  Foo* A = new Foo;
  FooPtr APtrOjb(A);
  printf("Is valid?: %s\n", APtrOjb.valid() ? "Valid" : "Not Valid");
  delete A;
  printf("Is valid?: %s\n", APtrOjb.valid() ? "Valid" : "Not Valid");
}

创建类 Foo 的对象时,它会获得一个永远不能为零的唯一 ID,当对象被删除时,析构函数会将唯一 ID 设置为零。然后 FooPtr 类型的对象可以通过检查 id 是否匹配来检查类 Foo 的对象是否仍然处于事件状态。

注意:我意识到检查 id 并不能 100% 授予结果,因为当内存被分配用于其他目的时,匹配发生的可能性很小。那么让我们假设身份验证方法可以被加强到 grantee 100% 结果,这是一个可行的解决方案吗?

有人建议这个问题类似于C++ delete - It deletes my objects but I can still access the data? ,但他的问题是关于删除数据,而我的问题是关于检测对象是否已被删除。

最佳答案

这是非常糟糕的,在一般情况下访问已删除的对象就好像它们没有被删除一样会崩溃。无法保证内存仍映射到进程内部,这可能会导致虚拟内存页面错误。

也有可能内存会被同一个类的不同实例重新使用,所以它看起来是有效的,但事实并非如此。

通常,这种设计会导致很难分析的错误。

您的测试程序的范围也非常有限。它无法说明大型程序的行为。

关于c++ - 检查已删除对象的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30983932/

相关文章:

c++ - ICU:ucnv_convertEx——即时检测编码错误

c++ - 无法编译 cpp-netlib 示例

c++ - 如何优化路径列表中的目录列表?

C++如何停止倒数计时器?

c++ - 带有 enumwindows 接口(interface)和进程的程序列表

c++ - 如何将此动态链接库链接到程序?

c++ - 从我正在扩展的嵌套类中覆盖方法

c++ - 为什么只能在头文件中实现模板?

c++ - 如何为 Visual Studio 代码设置 boost

c++ - 在 Windows 10 上的 Qt5 中围绕屏幕区域绘制高亮边框