Mingw32-w64 GCC 4.9.2正则表达式错误,还是我不了解C++?

Jon*_*ggs 3 c++ regex gcc scope c++11

#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 << ", ";
    }
}
Run Code Online (Sandbox Code Playgroud)

这让我疯了一段时间.这个程序在我的机器上轰炸,它在打印令牌时会陷入某种循环,tokens2直到它出现段错误.如果取消注释指示的行,程序将运行.但是,只tokens1包含正确拆分的令牌,我看不出差异在哪里.

这是一个简化的最小示例,它使用WinXP SP3,Code :: Blocks以及从Sourceforge(今天)Mingw64 GCC 4.9.2 for win32重新下载的机器上的行为.我对GCC 4.9.2的TDM-GCC-W32版本有同样的行为.

显然这些必须是2个错误吗?或者我真的不懂C++?

Pra*_*ian 5

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

C++ 14通过添加deleted rvalue重载来解决这个问题,这些重载会阻止你的第二个例子进行编译.

  • 男人......我一直在喝垃圾收集koolaid太久了... (2认同)