为什么我会收到警告:不要取消引用可能无效的指针

Why do I get the warning: Don't dereference a pointer that may be invalid

提问人:Ortwin 提问时间:9/2/2021 最后编辑:NathanOliverOrtwin 更新时间:9/2/2021 访问量:212

问:

启用 C++ 核心准则生存期检查 (Visual Studio 2019) 后,以下代码会生成我不明白的警告:

std::list<std::string> getKeys(const std::map<std::string, int>& entities)
{
   std::list<std::string> rc;
   for (auto const& el : entities)
   {
      rc.push_back(el.first);
   }
   return rc;
}

警告:

Don't dereference a pointer that may be invalid: '&el->first'.
'el.std::pair<std::basic_string<char,std::char_traits<char>,std::allocator<char> > const ,int>::first' 
may have been invalidated at line 67* (refers to the for-statement)

谁能解释为什么使用对 const 集合的引用进行迭代会导致无效指针?

C++ CPP 核心指南

评论

3赞 Cory Kramer 9/2/2021
这似乎是无稽之谈,该代码中没有任何内容会引起对生存期问题的担忧
12赞 NathanOliver 9/2/2021
奇怪的是,警告与代码不匹配。警告说的是 ,但您使用 .您确定此警告来自此确切的代码吗?&el->firstel.first
3赞 molbdnilo 9/2/2021
看起来像一个过于激进的静态分析工具。Microsoft 经常这样做。
1赞 NathanOliver 9/2/2021
那么这是一个误报。它可能认为你在添加它时正在迭代,这是一个问题,但不是你在做什么。rc
2赞 NathanOliver 9/2/2021
实际上什么都没有,我虽然它是一个向量,而不是一个列表。我现在不知道为什么它认为有问题。向 MS 提交错误报告。

答: 暂无答案