c++linked-list

Does deleting an object invoke its elements destructor?


I have a singly linked list that consists of a pointer to its next node and data (which is a pointer to an object). My question is: if I delete a node from the linked list using delete, will the object that the node was pointing to also be deleted, or will I end up with a dangling pointer? Will the destructor of the object be invoked in this case?


Solution

  • Generally, the answer is no: the data your node points to will not be deleted automatically when you delete node, because there is no rule in C++ to do it. But if the destructor of your Node class calls delete data, then the data will be deleted. You can do the following to check it: implement destructor for your data object class or put a breakpoint in existing destructor and then debug code that calls delete node. If you need the data to be destroyed when you delete the node, make sure the Node destructor calls delete data, like so:

    #include <iostream>
    class Data 
    {
      public: ~Data() 
      { // set a breakpoint on this line or check console output
        std::cout << "data destructor is called...";
      }
    };
    class Node 
    {
      Data* data;
      Node* next;
    public: 
      Node() {}
      Node(Data* _data):data(_data) {}
      ~Node() 
      {
        // delete data when the node is deleted
        delete data;
      }
    };
    int main() {
        std::cout << "create node...";
        Node* node = new Node();
        std::cout << "delete node...";
        delete node;
        std::cout << "deleted node." << std::endl;
    
        std::cout << "create node with data...";
        Node* nodeWithData = new Node(new Data());
        std::cout << "delete node with data...";
        delete nodeWithData;
        std::cout << "deleted node with data.";
    
        return 0;
    }
    

    The sample code is just to illustrate the relation between deleting node and deleting data object.

    EDIT 9/27/2023: Removed if(data) before delete data per viraltaco_'s suggestion in comments. Added sample main() method that creates and then deletes nodes. When the program runs you should get the following output:

    create node...delete node...deleted node.
    create node with data...delete node with data...data destructor is called...deleted node with data.