Automatic destruction of object even after calling destructor explicitly

后端 未结 5 1634
野趣味
野趣味 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:39

    the scope of t is the main function. Its created on the stack and will be destroyed at the end of the function.

    That's how its supposed to work and when you call the destructor on it early, you don't change that.

    You don't need to call the destructor and in this case doing so leads to it being called twice.

    if you'd used

    Test* t = new Test();
    

    the destructor would not have been automatically called at the end of main.

提交回复
热议问题