我在多图中使用对象作为关键字,如下所示。我只有一个类数据实例: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
将记录添加到拷贝构造函数中也是 – doctorlove
..和移动构造函数。移动对象仍然被销毁。 – MSalters