Automatic destruction of object even after calling destructor explicitly

后端 未结 5 1632
野趣味
野趣味 2021-01-23 09:05

The following program :

#include 
using namespace std;

class Test
{
public:
    Test() { cout << \"Constructor is executed\\n\"; }
    ~Te         


        
5条回答
  •  遥遥无期
    2021-01-23 09:25

    The compiler does not care if you called the destructor explicitly or not. The local object t gets out of scope, that's why it gets destroyed and the destructor is called. It is no good practice to call destructors explicitly. Instead you should write a method like cleanup() that can be called explicitly as well as from within the destructor. If you want to avoid that cleanup can be called twice, add something like this to you class:

    private:
    bool cleanupPerformed;
    
    void cleanup()
    {
       if( !cleanupPerformed )
       {
           // ... do cleanup work here ...
           cleanupPerformed = true;
       }
    }
    

提交回复
热议问题