为什么在使用对象作为多映射中的键时,驱动器被称为远远不够
Why is destructor being called more than enough when using an object as key in a multimap
我正在使用对象作为多件中的键,如下所示。我只有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
插入实际地图。
有关额外的洞察力和理解水平
相关文章:
- GetShortPathName在网络驱动器上使用中文文件夹时失败
- 在QTreeView中仅显示共享驱动器和文件夹
- 为什么程序员同时使用 std::bad_alloc 和 std::exception.是否 std::例外 仅是不够的
- QT MYSQL 驱动器构建,未定义对"mysql_get_client_version@0"的引用
- 通过搜索硬盘驱动器查找文件目录
- 如何确定SSD驱动器是固定驱动器还是连接在USB上
- 关于从驱动器中删除文件的问题
- 如何使用libusb获取驱动器名称?
- 如何确定文件或文件夹是在SSD还是硬盘驱动器上?
- 在鼠标按下时移动 SDL2 窗口的功能闪烁窗口并且移动速度不够快
- Qt驱动器下拉列表仅列出USB记忆棒
- 为什么我们需要构建一个提升库,仅仅包含头文件还不够吗,因为提升是模板
- C++ gtkmm:文件选择器对话框不适用于任何驱动器
- 使用 MFC c++ 删除已装载驱动器的文件
- 阻止访问映射的网络驱动器
- 驱动器号上的查找文件失败,但在路径上传递
- 将硬盘驱动器上的 BIT XXX 从 0 更改为 1
- 更改 ICDBurn 窗口 API 中的默认刻录驱动器
- C 操作员超载调用驱动器
- 为什么在使用对象作为多映射中的键时,驱动器被称为远远不够