Why does BOOST_FOREACH not work sometimes with C++

2019-07-15 05:32发布

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

2条回答
2楼-- · 2019-07-15 06:16

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
查看更多
该账号已被封号
3楼-- · 2019-07-15 06:16

You should give us more information about your code, because:

  • Your problem is tied with the VC++ runtime used
  • As plainly answered by Dmitriy, your problem is most probably caused by the body of the loop

Anyway, with the little info you gave us, I could speculate the following:

  • The fact the problem happens on debug and not on release is perhaps because a debug check discovered an error, memory corruption, whatever.
  • The fact it happens only when you switch runtime, with STL code is perhaps you are mixing code from different modules, each one compiled with a different runtime

Of course, the fact your iterating over a const string means nothing should get modified, but as I was unable to reproduce your bug (pun intended), it is difficult to offer a definitive answer.

If you want more info, you need to provide us with the following info:

  • Is the string object coming from another module (another DLL, another LIB, another EXE), possibly compiled with another runtime ?
  • If you write the code by hand (using a plain old "for"), does it work ?
  • What is the exact error message ?
查看更多
登录 后发表回答