不幸的是,你掉进了陷阱。在 C++11 中的重载std::regex_match
你打电话的是
template< class STraits, class SAlloc,
class Alloc, class CharT, class Traits >
bool regex_match( const std::basic_string<CharT,STraits,SAlloc>& s,
std::match_results<
typename std::basic_string<CharT,STraits,SAlloc>::const_iterator,
Alloc
>& m,
const std::basic_regex<CharT,Traits>& e,
std::regex_constants::match_flag_type flags =
std::regex_constants::match_default );
因为它需要一个const&
to a std::string
您可以向它传递一个临时字符串。对你来说不幸的是std::regex_match
不适用于临时字符串。这就是为什么你会出现意想不到的行为。您尝试引用超出范围的数据。
C++14 通过添加解决了这个问题
template< class STraits, class SAlloc,
class Alloc, class CharT, class Traits >
bool regex_match( const std::basic_string<CharT,STraits,SAlloc>&&,
std::match_results<
typename std::basic_string<CharT,STraits,SAlloc>::const_iterator,
Alloc
>&,
const std::basic_regex<CharT,Traits>&,
std::regex_constants::match_flag_type flags =
std::regex_constants::match_default ) = delete;
所以你不能再传递临时字符串。
如果您不能使用 C++14,那么您需要确保没有将临时字符串传递给std::regex_match