c++ - 为什么 BOOST_FOREACH 有时不能用于 C++ 字符串?

标签 c++ visual-studio string boost

我正在使用 BOOST_FOREACH 循环访问 C++ 字符串的字符,如下所示:

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

    return;
}

这段代码适用于以下编译模式:

  • 多线程(发布)(/MT)
  • 多线程调试 (/MTd)
  • 多线程 DLL(发布版)(/MD)

它只会在这种模式下导致运行时错误(异常):

  • 多线程调试 DLL(发布版)(/MDd)

上面的代码片段没有编译错误或警告,这让我相信 BOOST_FOREACH 知道它在这里处理的容器。此外,将 const char ch 更改为 const char& ch 不会改变行为。

为什么这段代码会导致这种不良的运行时行为?

为什么只在Debug DLL模式下?

BOOST_FOREACH 在 C++ 字符串上的这种用法是否错误?

如果是,最好的解决方法是什么?

(请注意,我正在使用 Visual Studio 2008 和 Boost 1.39。)

最佳答案

在 C++ 字符串上使用 BOOST_FOREACH 是绝对正确的(参见 http://www.boost.org/doc/libs/1_39_0/doc/html/foreach.html#foreach.introduction)。
看起来问题在

  
// Do something with ch

关于c++ - 为什么 BOOST_FOREACH 有时不能用于 C++ 字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1275852/

相关文章:

asp.net - 如何为 .NET 开发创建我的第一个数据库?

c++ - 错误 LNK2001 : unresolved external symbol when trying to use source and header files from another directory than the default in Visual Studio 2015

c - 返回字符串数组

c++ - C/C++ isspace() 跳过多字节字符串字符

c++ - 如何改进 std::vector 参数传递( move 语义?)

visual-studio - 为什么 AutoCAD 插件依赖于特定的 Visual Studio 版本?

c++ - 如何通过在 C++ 中创建对象来将参数传递给类?

python - 从字符串中删除所有标点符号,除非它在数字之间

c++ - 将 Windows 头文件包装在命名空间中安全吗?

java - 安卓ndk : Problem for call of Java method from c++ with jni