マルチマップでオブジェクトをキーとして使用しています。私はクラスデータのインスタンスが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
コピーコンストラクタにもログを追加します。 – doctorlove
..と移動コンストラクタ。移動したオブジェクトはまだ破壊されています。 – MSalters