为什么这两个sregex_iterator语句之间存在差异?

时间:2016-01-24 03:23:54

标签: c++ regex

这是第一个声明:

string s("hello.world");
sregex_iterator  pos(s.cbegin(), s.cend(), regex(R"(\.)"));
sregex_iterator end;
for (; pos != end; ++pos)
    cout << pos->str() << endl;

这是第二个声明:

string s("hello.world");
regex reg(R"(\.)");
sregex_iterator  pos(s.cbegin(), s.cend(), reg);
sregex_iterator end;
for (; pos != end; ++pos)
    cout << pos->str() << endl;

第二个程序可以正常运行,但第一个程序在运行时中止。 enter image description here

1 个答案:

答案 0 :(得分:2)

在这一行:

sregex_iterator  pos(s.cbegin(), s.cend(), regex(R"(\.)"));

expression regex(R"(\.)")对应于在函数调用后立即销毁的临时对象。所有迭代器都指向&#34;指向&#34;进入它是无效的。尝试使用此迭代器会导致调试运行时检查失败,并且正在抛出断言。

见: