为什么在使用对象作为多映射中的键时,驱动器被称为远远不够

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

本文关键字:驱动器 不够 被称为 映射 对象 为什么      更新时间:2023-10-16

我正在使用对象作为多件中的键,如下所示。我只有1个类数据的实例: 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;   
}

在输出中,击振子被称为3次。

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

您有多个实例。

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;
};

这将显示复制构造函数也被称为。

其他两个驱动器调用正在销毁最初拷贝构造的临时对象。向对象添加一个明确的复制构造函数,您会看到它被调用。

要弄清楚为什么要调用复制构建器,请观察到std::map::insert的参数是std::pair。现在,考虑一下,要实现这一事件的序列,必须考虑实际发生的事情:std::pair被构造,包含您的对象;为了使此std::pair插入实际地图。

有关额外的洞察力和理解水平