gpt4 book ai didi

c++ - 虚拟析构函数——谁调用底层的 free()?

转载 作者:搜寻专家 更新时间:2023-10-31 01:52:53 25 4
gpt4 key购买 nike

我想弄清楚使用虚拟析构函数从模块 B 中删除在模块 A 中创建的对象是否安全。

当使用 MS C++ 编译器时,删除具有虚拟析构函数的对象只会导致单个 vtable 调用,并且底层 free() 调用在它内部执行(即在创建对象,即安全)。

问题是:它只是当前的 MS 实现,还是在某些标准或文档中得到保证并且可以安全地依赖?

下面是 VS2010 中反汇编的虚拟析构函数调用示例:

int _tmain(int argc, _TCHAR* argv[])
{
test *p = new test();
008A1030 push 4
008A1032 call dword ptr [__imp_operator new (8A20A0h)]
008A1038 add esp,4
008A103B test eax,eax
008A103D je wmain+19h (8A1049h)
008A103F mov dword ptr [eax],offset test::`vftable' (8A2100h)
008A1045 mov ecx,eax
008A1047 jmp wmain+1Bh (8A104Bh)
008A1049 xor ecx,ecx
__asm int 3;
008A104B int 3
delete p;
008A104C test ecx,ecx
008A104E je wmain+28h (8A1058h)
008A1050 mov eax,dword ptr [ecx]
008A1052 mov edx,dword ptr [eax]
008A1054 push 1
008A1056 call edx
__asm int 3;
008A1058 int 3
return 0;
008A1059 xor eax,eax
}

最佳答案

嗯,调用者不会知道对象的类型?在不知道该类型的情况下,调用者如何调用 Derived::operator delete ?只有 Derived::~Derived 可以知道是否必须调用 Derived::operator delete 而不是通用的 ::operator delete

因此,我们可以推断调用者不能调用::operator delete

未指定 operator delete 稍后是否调用 free(),但无论如何这是一个细节。

关于c++ - 虚拟析构函数——谁调用底层的 free()?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11932155/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com