使用std shared_ptr作为std::map键
Using std shared_ptr as std::map key
我在徘徊-我可以使用std::shared_ptr
作为映射键吗?
更具体地说,指针的引用计数器可能与它赋值给map时的值不同。
它会在地图上被正确地识别吗?
是的,你可以…但是要小心。operator<
是根据指针定义的,而不是根据指向定义的。
int main() {
std::map<std::shared_ptr<std::string>, std::string> m;
std::shared_ptr<std::string> keyRef = std::make_shared<std::string>("Hello");
std::shared_ptr<std::string> key2Ref = std::make_shared<std::string>("Hello");
m[keyRef]="World";
std::cout << *keyRef << "=" << m[keyRef] << std::endl;
std::cout << *key2Ref << "=" << m[key2Ref] << std::endl;
}
打印
Hello=World
Hello=
可以。std::shared_ptr
以适合映射键使用的方式定义了operator<
。具体来说,只比较指针值,不比较引用计数。
显然,指向对象不是比较的一部分。否则,通过修改指向对象并使映射中的顺序与比较不一致,很容易使映射无效。
相关文章:
- 如何导出包含具有"std::unique_ptr"值的"std::map"属性的
- 使用一个考虑到std::map中键值的滚动或换行的键
- 有没有办法对std::unordered_set、std::unrdered_map、std::set、std::map
- 将重物插入std::map
- 使用通用值初始化 std::map,不重复
- 仅包含可移动 std::map 的类的移动构造函数不起作用
- C++:当所有条目都保证是唯一时,替代 std::map
- 使用模板化的键类型定义 std::map,该键类型基于作为参数接收的函数
- 如果 KEY 是 std::list 或 std::vector 而不是值,那么 std::map 的默认行为是什么?
- C++如何创建 std::map
- 从其他容器中移动构造"std::map"
- 将 std::map::emplace 与返回 shared_ptr 的函数一起使用是否正确?
- C++中 std::map 的运行时复杂度是多少?
- 为什么在 std::map 上移动无法将元素从一个映射移动到另一个映射
- 使用重载 [] 运算符返回 std::map() 的可赋值
- std::map, std::unordered_map - 缩小初始值设定项列表中的转换范围
- C++ 使用枚举类对象分配 std::map 值
- 静态 std::map instatiation 在类的方法中调用构造函数吗?
- std::map:当元素不可默认构造时创建/替换元素
- Arduino编译器和STL:使用std::vector和std::map