Search code examples
c++classdestructormultimap

Why is destructor being called more than enough when using an object as key in a multimap


I am using an object as a key in a multimap as follows. I only have 1 instance of class Data: Data d1(1,2).

#include <iostream>
#include <string>
#include <map>

using namespace std;

class Data{
    public:
        static int counter;
        Data(int x = 0, int y = 0):_x(x),_y(y){counter += 1; cout <<"constructor call " << counter << endl;}

        virtual ~Data()
        {
            counter -= 1;
            cout <<"calling destructor " << counter <<  endl;
        }

        bool operator<(const Data & right) const{
            return _x < right._x && _y < right._y;
        }
    private:
        int _x;
        int _y;
};

int Data::counter = 0;

int main()
{
 multimap<Data, string> m_map;

 Data d1(1,2);
 m_map.insert(make_pair(d1, "1"));

 return 0;   
}

In the output the destructor is being called 3 times.

constructor call 1
calling destructor 0
calling destructor -1
calling destructor -2

Solution

  • You have more than one instance.

    class Data {
    public:
        static int counter;
        Data(int x = 0, int y = 0) :_x(x), _y(y) { counter += 1; cout << "constructor call " << counter << endl; }
        Data(const Data & other) :_x(other._x), _y(other._y) { counter += 1; cout << "copy constructor call " << counter << endl; }
    
        virtual ~Data()
        {
            counter -= 1;
            cout << "calling destructor " << counter << endl;
        }
    
        bool operator<(const Data & right) const {
            return _x < right._x && _y < right._y;
        }
    private:
        int _x;
        int _y;
    };
    

    This will show the copy constructor being called too.