Home > database >  destructor not called for object going out of scope and end of main program
destructor not called for object going out of scope and end of main program

Time:09-04

I have the following code


#include <bits/stdc  .h>

struct TreeNode {
    int val;
    TreeNode *left;
    TreeNode *right;
    TreeNode() : val(0), left(nullptr), right(nullptr) {}
    TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
    TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
    ~TreeNode() {
        std::cout << "are we in here";
    }
};


int main()
{
    if(1 < 2) {
        TreeNode *testing = new TreeNode(15);
        //why is the destructor not called here?
    }
    TreeNode *root = new TreeNode(15);
    root->left = new TreeNode(10);
    root->right = new TreeNode(20);
    root->left->left = new TreeNode(8);
    root->left->right = new TreeNode(12);
    root->right->left = new TreeNode (16);
    root->right->right = new TreeNode(25);
    //why  is the destructor not being called here?
}

In the two comments, I was wondering why the destructor are not called there? If I remember correctly, when objects go out of scope, the destructor should be called. However, the TreeNode destructor is never called when the pointers go out of scope of the if statement and when main finishes

CodePudding user response:

One of the golden rules of C , if you use new on something, you also should delete it. When you use new, you are telling the compiler that you are now in charge of managing that variable's lifecycle.

  • Related