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

后端 未结 1 387
无人共我
无人共我 2021-01-18 06:08

I am using Visual Studio 2013 for development, which uses v12 of Microsoft\'s c++ compiler tools.
The following code executes fine, printing \"foo\" to the console:

1条回答
  •  醉话见心
    2021-01-18 06:57

    The reason is that get() returns a temporary string, so the match results contains iterators into an object that no longer exists, and trying to use them is undefined behaviour. The debugging assertions in the Visual Studio C++ library notice this problem and abort your program.

    Originally C++11 did allow what you're trying to do, but because it is so dangerous it was prevented by adding a deleted overload of std::regex_match which gets used when trying to get match results from a temporary string, see LWG DR 2329. That means your program should not compile in C++14 (or in compilers that implement the DR in C++11 mode too). GCC does not yet implement the change yet, I'll fix that.

    0 讨论(0)
提交回复
热议问题