regex_iterator 中不能直接构造 regex 对象

#include <iostream>
#include <string>
#include <regex>
using namespace std;

int main()
{
    string str = "1234-abcd-!@#$";
    //regex e("[^-]+");
    
    for (auto it = sregex_iterator(str.begin(), str.end(), regex("[^-]+"));  // 这里可以通过编译, 但是实际上是有问题的.
         it != sregex_iterator(); ++it)    
    {
        cout <<it->position() <<" : " <<it->str() <<endl;
    }

    return 0;
}

 

问题在于加红的语句.

程序在输出了一条街过后崩溃了. 原因是对于 sregex_iterator 而言, '++it' 操作会重复引用 sregex_iterator 的第三个参数, 也就是本里的加红部分, 但是 for 循环对 'it' 初始化后, 该参数就析构了, 因此后续的递增运算就出问题了.

正确的做法是声明一个 regex 对象, 如程序注释部分, 然后传入这个变量. 这个变量至少要和 ++/-- 运算的生命周期一样, 或者更长.

 

 

posted @ 2013-02-07 15:27  walfud  阅读(812)  评论(0编辑  收藏  举报