我刚写了一些代码,我试图理解对象是如何被多态破坏的。
#include <iostream>
struct Base {
virtual ~Base() {
std::cout << "base destructed\n";
}
};
struct Derived : public Base{
virtual ~Derived() {
std::cout << "derived destructed\n";
}
};
int main() {
Derived der;
Base bases1[2], bases2[2], bases3[2], bases4[2];
//case 1
new(bases1) Derived(der);
std::cout << "((Base*)bases1)->~Base();\n";
((Base*)bases1)->~Base();
//case 2
new(bases2) Derived(der);
std::cout << "\nbases2->~Base();\n";
bases2->~Base();
//case 3
new(bases3) Derived(der);
std::cout << "\nbases3[0].~Base();\n";
bases3[0].~Base();
//case 4
new(bases4) Derived(der);
std::cout << "\n(*bases4).~Base();\n";
(*bases4).~Base();
getchar();
return 0;
}
输出:
((Base*)bases1)->~Base();
derived destructed
base destructed
bases2->~Base();
bases3[0].~Base();
base destructed
(*bases4).~Base();
base destructed
以下是我从反汇编窗口获得的内容:
((Base*)bases1)->~Base();
00D96CF9 mov esi,esp
00D96CFB push 0
00D96CFD mov eax,dword ptr [bases1]
00D96D00 lea ecx,[bases1]
00D96D03 mov edx,dword ptr [eax]
00D96D05 call edx
00D96D07 cmp esi,esp
00D96D09 call __RTC_CheckEsp (0D91992h)
bases2->~Base(); //empty
bases3[0].~Base();
00D96DB0 push 0
00D96DB2 mov eax,4
00D96DB7 imul eax,eax,0
00D96DBA lea ecx,bases3[eax]
00D96DBE call Base::`vector deleting destructor' (0D91A0Ah) //array delete?
(*bases4).~Base();
00D96E14 push 0
00D96E16 mov eax,4
00D96E1B imul eax,eax,0
00D96E1E lea ecx,bases4[eax]
00D96E22 call Base::`vector deleting destructor' (0D91A0Ah) //aray delete?
我无法阅读汇编程序,有人能给我一个合理的解释吗?
答案 0 :(得分:0)
new(bases1) Derived(der);
未定义的行为。 bases1
是Base
的数组。将Derived
类型的对象填入其中并没有做任何有意义的事情。