C++ – Why does BOOST_FOREACH not work sometimes with C++ strings

boostcstringvisual studio

I am using BOOST_FOREACH to iterate through the characters of a C++ string like this:

void foobar(const string& str)
{
    BOOST_FOREACH(const char ch, str)
    {
        // Do something with ch
    }

    return;
}

This piece of code works fine with the following compilation modes:

  • Multi-threaded (Release) (/MT)
  • Multi-threaded Debug (/MTd)
  • Multi-threaded DLL (Release) (/MD)

It causes runtime errors (exceptions) only in this mode:

  • Multi-threaded Debug DLL (Release) (/MDd)

There are no compilation errors or warnings with the above code snippet, leading me to believe that BOOST_FOREACH knows the container it is handling here. Also, changing const char ch to const char& ch has no change in the behaviour.

Why is this code causing this bad runtime behaviour?

Why only in the Debug DLL mode?

Is this usage of BOOST_FOREACH on C++ strings wrong?

If yes, what is the best workaround for it?

(Note that I am working with Visual Studio 2008 and Boost 1.39.)

Best Answer

Usage of BOOST_FOREACH on C++ strings is absolutely correct (see http://www.boost.org/doc/libs/1_39_0/doc/html/foreach.html#foreach.introduction).
Looks like the issue in

  
// Do something with ch
Related Topic