You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C++中创建存储指向其他unordered_map的指针的unordered_map编译报错,咨询原因及错误点

C++中创建存储指向其他unordered_map的指针的unordered_map编译报错,咨询原因及错误点

哈喽~我来帮你拆解这个编译报错的问题,核心原因其实是一个很容易忽略的const限定符匹配问题,咱们一步步分析:


一、报错代码的核心问题

先看你在main函数里的代码:

int main() {
    static const std::unordered_map<int, int> bla = {{0, 1}, {1, 2}};
    static const std::unordered_map<int, int> blo = {{3, 1}, {4, 2}};
    // 此处foo的value类型是【非const的unordered_map指针】
    static const std::unordered_map<int, std::unordered_map<int, int>*> foo = {{1, &bla}, {2, &blo}};
}

编译器报错的本质是指针的const限定符不匹配:

  • bla和blo是const std::unordered_map<int, int>类型,所以它们的地址&bla、&blo的实际类型是const std::unordered_map<int, int>*(带const的指针)
  • 但你定义的foo的value类型是std::unordered_map<int, int>*(不带const的指针)

C++严格禁止隐式地将const T*转换为T*(这会丢失const限定,违反类型安全),所以初始化列表里的每个键值对都无法被隐式构造为std::pair<int, std::unordered_map<int, int>*>,最终导致整个unordered_map的初始化失败。


二、能编译的代码为什么正常

再看你提到的可编译代码片段:

// myMap1、myMap2是全局/命名空间级的const unordered_map
const std::unordered_map<std::string, uint32_t> myMap1 = {{...}};
// mapOfMaps的value类型是【带const的unordered_map指针】
static const std::unordered_map<std::string, const std::unordered_map<std::string, uint32_t>*> mapOfMaps = {
    {"map1", &myMap1}, {"map2", &myMap2}
};

这里的类型完全匹配:

  • &myMap1的类型是const std::unordered_map<std::string, uint32_t>*
  • mapOfMaps的value类型正好也是const std::unordered_map<std::string, uint32_t>*

所以编译器可以顺利将初始化列表中的每个元素构造为对应的std::pair,完成unordered_map的初始化。


三、你的代码的修复方案

只需要修正foo的类型,让它的value类型匹配&bla的const指针类型即可:

int main() {
    static const std::unordered_map<int, int> bla = {{0, 1}, {1, 2}};
    static const std::unordered_map<int, int> blo = {{3, 1}, {4, 2}};
    // 将value类型改为带const的指针
    static const std::unordered_map<int, const std::unordered_map<int, int>*> foo = {{1, &bla}, {2, &blo}};
}

额外补充

你可能会疑惑函数内static变量的初始化顺序,但这不是本次报错的原因:函数内的static变量是按定义顺序初始化的,bla、blo的定义在foo之前,所以初始化foo时,bla和blo已经完成初始化,取它们的地址是安全的。

内容来源于stack exchange

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.08 08:58:03