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

236 views Asked by At

With C++ Core-Guidelines lifetime checking enabled (Visual Studio 2019), the following code produces a warning I don't understand:

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;
}

The warning:

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)

Can anyone explain why iterating using references to a const collection should lead to an invalid pointer?

0

There are 0 answers