【问题标题】:Mingw32-w64 GCC 4.9.2 regex bug, or me not knowing C++?Mingw32-w64 GCC 4.9.2 正则表达式错误,或者我不懂 C++?
【发布时间】:2015-03-19 08:43:13
【问题描述】:
#include <iostream>
#include <vector>
#include <regex>

using namespace std;

int main()
{
    char rs[] = R"((\s+)|([\r\n][\r\n]?))"; /* split on whitespace or newline */
    regex r(rs); // this regex declared like a local variable
    string s("foo  bar \t baz\nqux quux corge");

/* Part 1 */

    sregex_token_iterator
            first {begin(s), end(s), r, -1},
            last;
    vector<string> tokens1 {first, last};
    for(auto i : tokens1) {
        cout << i << ", ";
    }

/* Part 2 */

    cout << endl << endl << "inline:";
    //string regexstring(rs); // <<< uncomment for different behavior

    /* here, the regex is created inline */
    sregex_token_iterator
            first2 {begin(s), end(s), regex(rs), -1},
            last2;

    vector<string> tokens2 {first2, last2};

    for(auto i : tokens2) {
        cout << i << ", ";
    }
}

这让我发疯了一段时间。这个程序在我的机器上爆炸,当从tokens2 打印令牌时,它卡在某个循环中,直到它出现段错误。如果取消注释指示的行,程序将运行。但是,只有 tokens1 包含正确拆分的令牌,我看不出区别在哪里。

这是一个简化的最小示例,它重现了具有 WinXP SP3、Code::Blocks 和从 Sourceforge(今天)Mingw64 GCC 4.9.2 for win32 新下载的机器上的行为。我在 GCC 4.9.2 的 TDM-GCC-W32 版本中得到了相同的行为。

很明显,这些肯定是 2 个错误,对吧?还是我真的不懂 C++?

【问题讨论】:

    标签: c++ regex c++11 gcc scope


    【解决方案1】:

    regex_token_iterator 并不像在 第 2 部分 中那样使用临时的 regex 对象调用,因为它不存储 regex 实例的副本。 第 2 部分 导致未定义的行为,因为调用导致迭代器由于 regex 实例在表达式末尾被销毁而已经失效。

    C++14 fixes this problem 添加 deleted 右值重载,这会阻止您的第二个示例编译。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-02-05
      相关资源
      最近更新 更多