I'm on Visual Studio 2013 and I'm seeing what I think is a bug, I was hoping someone could confirm?
string foo{ "A\nB\rC\n\r" };
vector<string> bar;
for (sregex_iterator i(foo.cbegin(), foo.cend(), regex("(.*)[\n\r]{1,2}")); i != sregex_iterator(); ++i){
bar.push_back(i->operator[](1).str());
}
This code hits a Debug Assertion in the Visual Studio regex library:
regex_iterator
orphaned
If I define the regex
outside the for
-loop it's fine:
string foo{ "A\nB\rC\n\r" };
vector<string> bar;
regex bug("(.*)[\n\r]{1,2}");
for (sregex_iterator i(foo.cbegin(), foo.cend(), bug); i != sregex_iterator(); ++i){
bar.push_back(i->operator[](1).str());
}
Alternatively this works fine in a transform as shown in this question:
string foo{ "A\nB\rC\n\r" };
vector<string> bar;
// This puts {"A", "B", "C"} into bar
transform(sregex_iterator(foo.cbegin(), foo.cend(), regex("(.*)[\n\r]{1,2}")), sregex_iterator(), back_inserter(bar), [](const smatch& i){ return i[1].str(); });
Can someone confirm this is a bug?
No, this is not a bug. See LWG 2329 regex_match()/regex_search() with match_results should forbid temporary strings. This construct exhibits undefined behavior since it binds a temporary regex to const regex& and stores a pointer to it.
Also see C++14 STL Features, Fixes, And Breaking Changes In Visual Studio 14 CTP1 where this is listed as a fix.
In C++11 you are allowed to bind a temporary
regex
toconst regex &
which can lead to undefined behavior if the iterator is used outside of the lifetime of the temporary since it will store a pointer to it. This is a defect in the specification and it is not an error, although Visual Studio catches this with a debug assert.The following deleted overload was adding in C++14 to prevent this case, from cppreference:
and it says:
So this is not a
Visual Studio
bug since it is implementing the C++11 standard and this was not addressed via a defect report till later on. Bothclang
andgcc
using-std=c++14
or greater will produce an error with your first(see it live) and third(see it live) example. Visual Studio only started supporting some C++14 in VS 2015:We can see that LWG defect 2332: regex_iterator/regex_token_iterator should forbid temporary regexes deals with this:
As T.C. points out the last example you show is actually ok, even though you are binding a temporary its lifetime extends to the end of the expression.