文章目录
- 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
关注
打赏
热门博文
- 3D Assets (Textures & Model & Animations) & Game Design Ideas & DCC Tutorials & TA
- LearnGL - 学习笔记目录
- Unity - Timeline 知识汇总
- Unity Graphics - 知识点目录 - 停止翻译,因为发现官方有中文文档了
- Graphic资料
- Unity Lightmap&LightProbe局部动态加载(亲测2020以及以上版本官方修复了)
- Unity - 踩坑日志 - 低版本线性颜色空间渲染异常的 “BUG”
- Unity Shader - PBR 渲染 SP 导出的素材
- 什么是 3A 游戏?
- Photosohp - 实现 2D MetaBall、MetaFont