+ 4
How does the dead monkey shows its tail?
class Monkey { public: int taleLength = 3; void showTale() { cout << "Monkey says: 'My tale is " << taleLength << "m' \n"; } ~Monkey() { cout << "Monkey was killed by a poacher :(\n"; } }; int main() { Monkey* p; { Monkey Jack; p = &Jack; } p->showTale(); system("pause"); } Output: Monkey was killed by a poacher :( Monkey says: 'My tale is 3m' Destructor was called, but why does the Jack still exist?
2 ответов
+ 3
Poor old Jack still exists and is valid because the stack has not been cleaned yet, nor has it been overwritten. Let's look at the partial disassembly:
#stack allocation and setting up stack frame
push rbp
mov rbp, rsp
sub rsp, 16
#Creating Jack on the stack
lea rdi, [rbp - 16]
call Monkey::Monkey()
#Get the address of Jack
lea rdi, [rbp - 16]
#Store it in p
mov QWORD PTR [rbp-8], rax
#Call destructor
call Monkey::~Monkey()
#Call showTale, p is still pointing to valid stack memory, so this will work.
mov rdi, qword ptr [rbp - 8]
call Monkey::showTale()
#deallocate stack and return 0
xor eax, eax
add rsp, 16
pop rbp
ret
+ 6
I'm sorry, I don't know. But I definitely had to say this question's title made me laugh