Home > Mobile >  Destructors called without matching constructor
Destructors called without matching constructor

Time:01-16

I am trying to figure out how C resource management works, especially in relation to constructors/destructors. This is my test code;

ylist.h

#pragma once
template <class T>
struct ListNode
{
    T elem;
    struct ListNode* next;
    ListNode(T elem):elem(elem),next(nullptr) {}
};

template <class T>
class List
{
    ListNode<T> *head;

public:
    List() : head(nullptr)
    {

    }
    ~List()
    {
        ListNode<T>* cursor = head;
        while (cursor != nullptr)
        {
            ListNode<T>* next = cursor->next;
            delete cursor;
            cursor = next;
        }
    }
    void append(T item)
    {
        ListNode<T>* n = new ListNode<T>(item);
        if (head == nullptr)
        {
            head = n;
        }
        else
        {
            ListNode<T>* cursor = head;
            while (cursor->next != nullptr)
                cursor = cursor->next;
            cursor->next = n;
        }
    }
};

main.cpp

#include <iostream>
#include "ylist.h"

using namespace std;

class myObj
{
    int val;
public:
    myObj(int val):val(val)
    {
        cout << "myObj@" << this << "(" << val << ")" << endl;
    }

    ~myObj()
    {
        cout << "~myObj@" << this << "(" << val << ")" << endl;
    }

};

int main()
{
    List<myObj> myList;

    for (int i = 0; i < 3; i  )
    {
        myList.append(myObj(i));
    } 
}

And here is the output;

myObj@00000039614FFAC0(0)
~myObj@00000039614FFAD0(0)
~myObj@00000039614FFAC8(0)
~myObj@00000039614FFAC0(0)
myObj@00000039614FFAC0(1)
~myObj@00000039614FFAD0(1)
~myObj@00000039614FFAC8(1)
~myObj@00000039614FFAC0(1)
myObj@00000039614FFAC0(2)
~myObj@00000039614FFAD0(2)
~myObj@00000039614FFAC8(2)
~myObj@00000039614FFAC0(2)
~myObj@0000019878DF6100(0)
~myObj@0000019878DF5F20(1)
~myObj@0000019878DF6200(2)

According to above output, constructor called for each object once, but destructors called four times.

I was expecting to see multiple temporary copies being constructed/destructed but why is number of constructors/destructos is not matching.

If, for example, I was opening files or db connections on constructors and closing them on destructors, would I get in trouble in above scenario?

CodePudding user response:

Add this copy constructor to your myObj function in order to see how the additional myObj objects are being constructed. Once you have this, you'll see that the number of constructor-calls matches the number of destructor-calls.

myObj(const myObj & rhs):val(rhs.val)
{
    cout << "COPY CTOR myObj@" << this << "(" << val << ")" << endl;
}
  •  Tags:  
  • c
  • Related