Destructor being called twice when being explicitly invoked

后端 未结 10 469
孤街浪徒
孤街浪徒 2020-11-30 11:10

I was experimenting with destructors in C++ with this piece of code:

#include 

struct temp
{
    ~temp() { std::cout << \"Hello!\" <         


        
10条回答
  •  一个人的身影
    2020-11-30 11:30

    Calling the destructor does not free the object.

    The destructor is there to clean up the internals of the object and then the object itsself is freed after the destructor finishes.

    It's an error to do what you are doing similarly to the way that you can call delete twice on an object but it's an error to do so.

    There are only a very few cases where you want to call the destructor manually and this isn't one of them. It's really there for the times you manually construct an object at a memory location using placement new and then need to be able to destruct it without freeing the memory.

提交回复
热议问题