map元素在内存中是固定的吗?

C++: Are map elements stationary in memory?

本文关键字:元素 内存 map      更新时间:2023-10-16

我们是否可以说std::map的元素(对)是平稳的?用g++做一个快速测试,发现插入元素后,它会停留在内存中的同一位置。

定义:

struct K { ... }; // Holds an int, prints when constructed, destructed etc..
struct V { ... }; // Holds an int, prints when constructed, destructed etc..
typedef std::map<K,V> M;
M m;

调试第一次插入后的打印:

======= ADDRESS #1
DEBUG: M::const_iterator i = m.find(10)
K(10)
K.~K; value == 10
DEBUG: &*i == 0x1e6b030
DEBUG: &i->first == 0x1e6b030
DEBUG: &i->second == 0x1e6b034

调试后打印许多插入:

======= ADDRESS #2
DEBUG: M::const_iterator i = m.find(10)
K(10)
K.~K; value == 10
DEBUG: &*i == 0x1e6b030
DEBUG: &i->first == 0x1e6b030
DEBUG: &i->second == 0x1e6b034

在标准中是否有任何显式或隐式的保证元素在插入后仍保持在内存中的位置?我们有单独的键或值吗?

来自第23.1.2/8节(关联容器):

insert成员不能影响迭代器和对容器引用的有效性,也不能影响erase操作的有效性成员只能使迭代器和对已删除元素的引用失效。

所以map元素保证在内存中保持静止