Why does the C ++ regex_match function require the search string to be defined outside the function?

I am using Visual Studio 2013 for development, which uses Microsoft's C12 compiler tools v12.
The following code does a fine by typing "foo" on the console:

#include <regex> #include <iostream> #include <string> std::string get() { return std::string("foo bar"); } int main() { std::smatch matches; std::string s = get(); std::regex_match(s, matches, std::regex("^(foo).*")); std::cout << matches[1] << std::endl; } // Works as expected. 

The same code replacing the string "s" for the function "get ()" throws an error "string iterators incompatible" at runtime:

 #include <regex> #include <iostream> #include <string> std::string get() { return std::string("foo bar"); } int main() { std::smatch matches; std::regex_match(get(), matches, std::regex("^(foo).*")); std::cout << matches[1] << std::endl; } // Debug Assertion Failed! // Expression: string iterators incompatible 

It makes no sense to me. Can anyone explain why this is happening?

+7
c ++ regex visual-studio
source share
1 answer

The reason is that get() returns a temporary string, so the matching results contain iterators in an object that no longer exists, and trying to use them is undefined behavior. Debug statements in the Visual Studio C ++ library notice this problem and interrupt your program.

C ++ 11 initially allowed what you were trying to do, but since it was so dangerous, it was prevented by adding the remote overload std::regex_match , which is used when trying to get the results of a match from a time line, see LWG DR 2329 . This means that your program should not be compiled in C ++ 14 (or in compilers that implement DR in C ++ 11 mode). GCC is not making changes yet, I will fix it.

+10
source share

All Articles