奇怪的 sizeof(std::map)

Strange sizeof(std::map)

我正在使用 std::map,无法理解它消耗了多少内存。

我有以下地图定义:

CKey {
 long x;
 int y;
 int z;
 bool operator<(const CKey& l) const;
};

CValue {
 int data1;
 int data2;
}

std::map<CKey, CValue> map;
std::cout << "sizeof() = " << sizeof(map) << " Max #Elms = " << map.max_size();

(插入元素到地图之前或之后没有关系) 我明白了。

sizeof() = 48
Max_Size = 329406144173384850
  1. 如果sizeof(map) = 48,怎么会包含329406144173384850个元素呢?
  2. 地图是否将 <CKey,Cvalue> 保存在其他内存中(堆?)

在 C 和 C++ 中,sizeof 运算符告诉您 堆栈 space 的一个实例将占用多少字节 class .

与其他标准容器(std::array 除外)一样,map 在使用默认分配器时在 上分配其元素。这意味着它的静态大小(即 sizeof returns)不依赖于 map.

中的元素数量

您可以使用 size() 成员函数找出 map 中有多少个元素。另一方面,max_size() 成员函数告诉您 map 理论上可以存储多少个元素——在 64 位系统上,您几乎肯定会受到内存数量的限制系统而不是什么 max_size() returns.

实际上计算出 map 的总内存使用量(堆栈和堆)并不是一件容易的事:在 C++17 中你可以做类似

的事情
sizeof(map) + map.size() * sizeof(typename map::node_type);

给你一个粗略的猜测,但实际上这将取决于你的标准库的实现细节。

std::map定义了以下方法

max_size()

Returns the maximum number of elements the container is able to hold due to system or library implementation limitations

size()

Returns the number of elements in the container

因此,以下计算将为您提供地图实际大小的良好近似值 字节(假设密钥和值类型是基本类型的结构):

sizeof(mymap) + mymap.size() * (sizeof(decltype(mymap)::key_type) + sizeof(decltype(mymap)::mapped_type))