How does C++ automatically call destructor?
In C++, we can manage resources by objects, ie acquiring resource in Ctor, and releasing it in Dtor (RAII). This relies on C++'s automatic destructor invocation. But how is this done under the hood? For example, how C++ know to call Dtor for c1
but not c2
. (I know this must have been answered before, but all of my searches ended in topics explaining how to use RAII). Thanks!
class Cat;
Cat c1;
Cat* c2 = new Cat();
Edit: I know I need to call delete for c2
. I just don't understand how Dtor is called when c1
goes out of scope.
Take a look at compiler explorer. I've linked a buildable version of your example. Just in case the link is not permanent, I've copied the code at the end if this answer.
For the Cat c1;
line (in light red) you will see that there are three corresponding blocks in the asm, same colour.
lea rax, [rbp-28]
mov rdi, rax
call Cat::Cat()
This matches the construction of the object on the stack.
Next there is
lea rax, [rbp-28]
mov rdi, rax
call Cat::~Cat()
This is the normal return path, calling the destructor automatically.
Finally there is
lea rax, [rbp-28]
mov rdi, rax
call Cat::~Cat()
mov rax, rbx
mov rdi, rax
call _Unwind_Resume
This is the path taken if an exception is thrown (eg, by new
). It automatically calls the destructor and then continues the exception.
For the sake of completeness, here is the C++ source code:
class Cat
{
public:
Cat() : meow() {}
~Cat() {}
private:
int meow;
};
void foo()
{
Cat c1;
Cat* c2 = new Cat();
}
int main()
{
foo();
}
链接地址: http://www.djcxy.com/p/84322.html
上一篇: K&R C while循环省略了大括号
下一篇: C ++如何自动调用析构函数?