问题描述
最近,在使用自定义分配器代码和放置 new+delete 时,我注意到一些让我感到惊讶的事情:当调用虚拟析构函数时,它会写入对象即将被释放的内存。
这是为什么?
(更新) 旁白:我对这里的实际行为更感兴趣,而不是 C++ 标准所说的,我确定没有指定这种行为。
这里有一个小程序来演示:
#include <new>
#include <cstring>
#include <iostream>
using std::cout;
using std::endl;
struct Interface {
virtual ~Interface() = default;
};
struct Derived : public Interface {
};
alignas(Derived) unsigned char buffer[sizeof(Derived)];
int main() {
memset(buffer,0xff,sizeof(buffer));
cout << "Initial first byte: 0x" << std::hex << (int)buffer[0] << endl;
// Create an instance,using 'data' as storage
Derived *pDer = ::new (buffer) Derived();
cout << "After ctor,first byte: 0x" << std::hex << (int)buffer[0] << endl;
pDer->~Derived();
cout << "After destroy,first byte: 0x" << std::hex << (int)buffer[0] << endl;
return 0;
}
实时链接:https://godbolt.org/z/jWv6qs3Wc
输出如下:
Initial first byte: 0xff
After ctor,first byte: 0x68
After destroy,first byte: 0x88
如果我删除虚拟 Interface
,那么内存根本不会改变,正如预期的那样。
这是某种调试功能吗?
这似乎是特定于编译器的。 Clang 不会这样做,但 GCC 会这样做。
它似乎随着 -O2
消失了。但是,我仍然不确定它的目的。
解决方法
要销毁一个Derived
,在概念上调用Derived::~Derived
(在这种情况下什么都不做),然后调整vtable,使对象是Interface
,然后{{1 }} 叫做。您观察到的是指向 Interface::~Interface
虚表的指针(如所见 here,构造 Interface
给出相同的第一个字节)。
如果您启用优化,那么由于 Interface
什么都不做,Interface::~Interface
也可以优化为无操作,并且您会看到打印的第一个字节相同。