I'm currently converting my code to C++11 and having trouble with the following range-based for loop (FWIW, the same code ran just fine before with BOOST for_each).

The mLibraryFiles member (STL vector) is part of a singleton instance and guaranteed to exist after the method returns, however when the caller inspects the returned object it contains only garbage.

Debugging through it appears to turn from expected content to garbage just after returning from the method so I suppose I must have gotten something wrong about how the C++11 range-based loop actually works:

Entry* FindEntry(string inName)
{  Entry *rs = NULL;

   for (auto libraryEntry : mLibraryFiles)
   {
      if (libraryEntry.filename.compare(inName) == 0)
      {
         rs = &libraryEntry;
         break;
      }
   }

   return rs;
}

I would have expected that the libraryEntry variable represents the actual objects in the mLibraryFiles vector?

Any insights much appreciated!
(compiler is LLVM 5.0 though I doubt this matters..)

有帮助吗?

解决方案

The values from your vector are copied to libraryEntry in the loop, so you have a pointer to copied value which no longer exists after the loop. Use auto& libraryEntry.

其他提示

Declare libraryEntry as auto& otherwise its a temporary copy which lifetime is bound to the for-loop. Thats why I prefer to write the actual type of the object instead of auto

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top