作者热门文章
- android - RelativeLayout 背景可绘制重叠内容
- android - 如何链接 cpufeatures lib 以获取 native android 库?
- java - OnItemClickListener 不起作用,但 OnLongItemClickListener 在自定义 ListView 中起作用
- java - Android 文件转字符串
是否可以在 C++ 中将已删除对象的内存清零?我想这样做以在单元测试中重现核心转储:
//Some member variable of object-b is passed-by-pointer to object-a
//When object-b is deleted, that member variable is also deleted
//In my unit test code, I want to reproduce this
//even if I explicitly call delete on object-b
//accessBMemberVariable should coredump, but it doesn't
//I'm assuming even though object-b is deleted, it's still intact in memory
A *a = new A();
{
B *b = new B(a);
delete b;
}
a->accessBMemberVariable();
最佳答案
您可能应该覆盖 delete
运算符。
给定类 B 的示例:
class B
{
public:
// your code
...
// override delete
void operator delete(void * p, size_t s)
{
::memset(p, 0, s);
::operator delete(p, s);
}
};
编辑:感谢 litb 指出这一点。
关于c++ - 如何在 C++ 中清理已删除的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/880269/
我是一名优秀的程序员,十分优秀!