Destructor being called twice when being explicitly invoked

后端 未结 10 455
孤街浪徒
孤街浪徒 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:36

    The destructor of a class could be invoked:

    1. Explicitly

      When the destructor is explicitly invoked using the object of the class, the same way you invoke another member function of the class.

    2. Implicitly

      When the object of the class goes out of scope or an object which is created using the new operator is destroyed using the delete operator.

    In your sample program, you do both

    int main()
    {
      temp t;
    
      t.~temp(); //1. Calling destructor explictly using the object `t`
    
      return 0;
    } // 2. object `t` goes out of scope. So destructor invoked implictly
    

    and that is the reason why you see the destructor being called twice.

    As you have aptly thought, the destructor will destroy the resources which were created by constructor. So the destrutor should not be called explicitly, as it will result in destroying the already destroyed resource and that could be fatal.

提交回复
热议问题