Search code examples
c++classdestructordoubly-linked-list

Why class destructor called if I delete linked list element?


I want to free memory by deleting all nodes in the end of programm, but I also have function(overloaded operator) to delete specific node. If I'm deleting specific node class destructor is called. Can someone explain why, and how to fix it.

Class declaration

class StudentList
{
    private:
        typedef struct student_node
        {
            student_node* prevSt;
            
        //######Student DATA######
            string surname;
            string name;
            string father_name;
            Date birthday;
            int year;
            string faculty;
            string departament;
            string group;
            string ID_number;
            string sex; 
        //########################
            SessionList session_data;
            int session_count;
        //########################
        
            student_node* nextSt;       
        }* student_nodePtr;
    
        student_nodePtr headSt;
        student_nodePtr currSt;
        student_nodePtr tailSt;
        student_nodePtr tempSt;
            
    public:
        StudentList();
        ~StudentList();
        StudentList operator-(student_nodePtr selectedSt);
};

Constructor, destructor and overloaded operator

StudentList::StudentList()
{
    headSt = NULL;
    currSt = NULL;
    tailSt = NULL;
    tempSt = NULL;
}

StudentList::~StudentList()
{
    cout << "What!?" << endl;
}

StudentList StudentList::operator-(student_nodePtr selectedSt)
{
    if(headSt == NULL || selectedSt == NULL)
    {
        return *this;
    }
    
    if(headSt == selectedSt)
    {
        headSt = selectedSt->nextSt;
    }
    
    if(tailSt == selectedSt)
    {
        tailSt = selectedSt->prevSt;
    }
    
    if(selectedSt->prevSt != NULL)
    {
        selectedSt->prevSt->nextSt = selectedSt->nextSt;
    }
    
    delete selectedSt;
    return *this;
}

Here i'm choosing to Delete (2 2 2 2) guy

Here destructor appears for some reason


Solution

  • You've declared your operator- like this:

        StudentList operator-(student_nodePtr selectedSt);
    

    Note that it is returning a StudentList object by-value. That means that the calling code is receiving a temporary StudentList object, which then gets destroyed when it goes out of scope; hence the call to the StudentList destructor.

    The usual way to declare an operator like that would by to have it return a reference instead:

        StudentList & operator-(student_nodePtr selectedSt);
    

    ... that way no temporary StudentList object is created, but calls to the operator can still be chained together if desired.