Question

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..)

Was it helpful?

Solution

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.

OTHER TIPS

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top