This page is a snapshot from the LWG issues list, see the Library Active Issues List for more information and the meaning of C++14 status.

2329. regex_match()/regex_search() with match_results should forbid temporary strings

Section: 32.3 [re.syn] Status: C++14 Submitter: Stephan T. Lavavej Opened: 2013-09-21 Last modified: 2016-01-28

Priority: 2

View all other issues in [re.syn].

View all issues with C++14 status.

Discussion:

Consider the following code:

const regex r(R"(meow(\d+)\.txt)");
smatch m;
if (regex_match(dir_iter->path().filename().string(), m, r)) {
  DoSomethingWith(m[1]);
}

This occasionally crashes. The problem is that dir_iter->path().filename().string() returns a temporary string, so the match_results contains invalidated iterators into a destroyed temporary string.

It's fine for regex_match/regex_search(str, reg) to accept temporary strings, because they just return bool. However, the overloads taking match_results should forbid temporary strings.

[2014-02-13 Issaquah: Move as Immediate]

Proposed resolution:

This wording is relative to N3691.

  1. Edit 32.3 [re.syn], header <regex> synopsis, as indicated:

    #include <initializer_list>
    
    namespace std {
    
      […]
      
      // 28.11.2, function template regex_match:
      […]
      template <class ST, class SA, class Allocator, class charT, class traits> 
      bool regex_match(const basic_string<charT, ST, SA>&&, 
                       match_results<
                         typename basic_string<charT, ST, SA>::const_iterator, 
                         Allocator>&, 
                       const basic_regex<charT, traits>&, 
                       regex_constants::match_flag_type = 
                         regex_constants::match_default) = delete;
    
      // 28.11.3, function template regex_search:
      […]
      template <class ST, class SA, class Allocator, class charT, class traits> 
      bool regex_search(const basic_string<charT, ST, SA>&&, 
                        match_results<
                          typename basic_string<charT, ST, SA>::const_iterator, 
                          Allocator>&, 
                        const basic_regex<charT, traits>&, 
                        regex_constants::match_flag_type = 
                          regex_constants::match_default) = delete;
      […]
    }