您当前的位置: 首页 >  c++

Jave.Lin

暂无认证

  • 3浏览

    0关注

    704博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文

C++ 如何判断一个对象是否被删除、统一管理对象

Jave.Lin 发布时间:2020-08-07 09:06:31 ,浏览量:3

文章目录
  • BUG
  • 解决方式
    • 完整测试例子

之前写了一篇:C++ 统一管理对象的删除,使用指针的指针**,或是指针的引用*&

BUG

其实发现这种写写法很有问题: 在这里插入图片描述

因为如果一个对象被 delete 后,或是 free 后,随时都有可能会立刻被分配到其他地方的内存使用了。

所以 当前对象 this 或是 this 中的 char* _isDestroy 成员就有可能会被其他程序分配到一个我们这个程序中不可访问的内存地址中去,这时要是通过以下原来的判断方式就会出错: 在这里插入图片描述

可能会报 this 内存地址不可访问。

那么也就是说,一旦我调用 bool isDestroy() 方法后,有可能都会报错,所以我们不能取访问一个野指针的 this 的内部数据了。

解决方式

使用一个 set 来记录对象内存地址即可 在这里插入图片描述

声明一个 std::unorder_set,并在构造函数插入内存地址、在析构函数删除地址、在 isDestroy() 查询地址即可: 在这里插入图片描述

这样就可以避开调用野指针 this 的内部数据调用,只是判断 this 地址是否在我们的管理对象的地址中即可。

完整测试例子
// jave.lin - 测试 Object 对象的统一管理删除
#include
#include
#include

// Check GCC
#if __GNUC__
#   pragma message("compiling in GNUC, GCC")
#   if __x86_64__ || __ppc64__
#       pragma message("64 bits computer")
#       define ENVIRONMENT64
#   else
#       pragma message("32 bits computer")
#       define ENVIRONMENT32
#   endif
#else
// Check windows
#   pragma message("compiling Not in GNUC, GCC")
#   if _WIN32 || _WIN64
#       pragma message("compiling in Window32/64")
#       if _WIN64
#           pragma message("64 bits computer")
#           define ENVIRONMENT64
#       else
#           pragma message("32 bits computer")
#           define ENVIRONMENT32
#       endif
#   endif
#endif

#ifdef ENVIRONMENT32
using address_t = unsigned int;
#else
using address_t = unsigned long long;
#endif

#define P(content) std::cout             
关注
打赏
1664331872
查看更多评论
0.0755s