【问题标题】:regex_token_iterator issue in Visual Studio 2015 Update 2 RCVisual Studio 2015 Update 2 RC 中的 regex_token_iterator 问题
【发布时间】:2016-03-19 05:44:11
【问题描述】:

我安装了 Visual Studio 2015 Update 2 Release Candidate,现在似乎在使用 sregex_token_iterator 时遇到了问题,到目前为止似乎工作正常。为了验证我从cppreference.com 尝试了以下示例代码(请注意,我将变量text 更改为末尾有一个空格):

#include <iostream>
#include <regex>

int main() {
    std::string text = "Quick brown fox ";
    // tokenization (non-matched fragments)
    // Note that regex is matched only two times: when the third value is obtained
    // the iterator is a suffix iterator.
    std::regex ws_re("\\s+"); // whitespace
    std::copy(std::sregex_token_iterator(text.begin(), text.end(), ws_re, -1),
              std::sregex_token_iterator(),
              std::ostream_iterator<std::string>(std::cout, "\n"));
}

运行它会给出以下断言:

Debug Assertion Failed!

Program: C:\WINDOWS\SYSTEM32\MSVCP140D.dll
File: c:\program files (x86)\microsoft visual studio 14.0\vc\include\xstring
Line: 247

Expression: string iterators incompatible

For information on how your program can cause an assertion
failure, see the Visual C++ documentation on asserts.

这是 Visual Studio STL 实现中的错误还是 regex_token_iterator 的示例错误?

【问题讨论】:

  • cppreference.com 示例严格遵守标准,错误发生在 C 运行时而不是抛出异常,所以我确定这是 STL 实现中的错误。至少 MSVC 开发人员非常聪明地为这种预期情况添加了断言。
  • 我建议使用 boost 正则表达式,STL 正则表达式的实现通常是错误的(至少对我而言),切换到 boost 只需要更改命名空间。

标签: c++ visual-c++


【解决方案1】:

对此感到抱歉——作为我们在 &lt;regex&gt; 中为更新 2 所做的性能修复的一部分,我们不再制作大量的临时字符串对象;如果 sub_match 实例不匹配某些东西,我们只需创建值初始化的迭代器,其行为“好像”有一个空字符串匹配。

这个程序应该从 C++14 开始有效(并且在道德上是 regex_token_iterator 内部发生的事情);见“null forward iterators”:

#include <stdio.h>
#include <string>

int main() {
    // Value constructed iterators conceptually point to an empty container
    std::string::iterator beginIt{};
    std::string::iterator endIt{};
    printf("This should be zero: %zu\n", endIt - beginIt);
}

...但是我们的调试断言禁止这样做。 regex_token_iterator 刚好被它绊倒了。

请注意,在发布版本(关闭调试断言)中,这一切都可以正常工作;错误在于迭代器调试机制,而不是迭代器的行为。

此错误将在 2015 Update 2 RTM 中修复。

【讨论】:

    猜你喜欢
    • 2015-10-31
    • 1970-01-01
    • 1970-01-01
    • 2017-01-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-11
    相关资源
    最近更新 更多