Simple std::regex_search() code won't compile with Apple clang++ -std=c++14

后端 未结 3 653
-上瘾入骨i
-上瘾入骨i 2020-12-07 01:23

Here is the MCVE:

#include 
#include 

std::string s()
{
    return \"test\";
}

int main()
{
    static const std::regex regex(         


        
3条回答
  •  有刺的猬
    2020-12-07 01:36

    There was a change going from C++11 to C++14 where std::regex_search is no longer allowed to take a r-value

    template< class STraits, class SAlloc,
              class Alloc, class CharT, class Traits >
    bool regex_search( const std::basic_string&&,
                       std::match_results<
                           typename std::basic_string::const_iterator, 
                           Alloc>&,
                       const std::basic_regex&,
                       std::regex_constants::match_flag_type flags =
                           std::regex_constants::match_default ) = delete;
    

    This was added as the overload that takes a const std::string&

    is prohibited from accepting temporary strings, otherwise this function populates match_results m with string iterators that become invalid immediately.

    So you can no longer pass a temporary to std::regex_search as of C++14

    To fix your code we would simply store the return from s() into a variable in main and use that to call std::regex_search.

    #include 
    #include 
    
    std::string s()
    {
        return "test";
    }
    
    int main()
    {
        static const std::regex regex(R"(\w)");
        std::smatch smatch;
    
        auto search = s();
        if (std::regex_search(search, smatch, regex)) {
            std::cout << smatch[0] << std::endl;
        }
    
        return 0;
    }
    

    Live Example

提交回复
热议问题