-1

Can someone kindly explain why in the code below there is one line that generates an error ? For comparison, the next line compiles correctly. For some reasons, the casting to std::string is not the same as suppling a std:: string type variable. I am using Visual Studio 2019, C++, console application with default options.

#include <iostream>
#include <regex>

int main()
{
    std::regex e;
    std::smatch sm;
    std::string str("abc");
    std::regex_search(std::string("abc"), sm, e);  // Doesn't compile
    std::regex_search(str, sm, e);  // Compiles correctly
}

Here's the error given by the pre-compiler Sorry for the italian...

Gravità Codice Descrizione Progetto File Riga Stato eliminazione Errore (attivo) E1776 impossibile fare riferimento a funzione "std::regex_search(const std::basic_string<_Elem, _StTraits, _StAlloc> &&, std::match_results::const_iterator, _Alloc> &, const std::basic_regex<_Elem, _RxTraits> &, std::regex_constants::match_flag_type = std::regex_constants::match_default) [con _StTraits=std::char_traits, _StAlloc=std::allocator, _Alloc=std::allocator, std::_String_iter_types>>>>>, _Elem=char, _RxTraits=std::regex_traits]" (dichiarato alla riga 2300 di "C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\VC\Tools\MSVC\14.24.28314\include\regex"). È una funzione eliminata ConsoleApplication3 C:\Users\munarid\source\repos\Unit-Test-Generation_Support\ConsoleApplication3\ConsoleApplication3.cpp 9

quinzio
  • 40
  • 7
  • You should include the compiler's error message in your question :) – Florian Humblot Jan 29 '20 at 08:07
  • 1
    If you visited this [web](https://en.cppreference.com/w/cpp/regex/regex_search) , you would see `= delete` at the overload you want to call. So it is not surprising it doesn't compile. – rafix07 Jan 29 '20 at 08:11

1 Answers1

1

That overload was deleted in C++ 2014.

The smatch result is a string iterator, and an iterator into the temporary argument object would be invalid as soon as the function returns.

molbdnilo
  • 64,751
  • 3
  • 43
  • 82
  • Ok, fine. I apologize for my limited knowledge of C++. My doubts remain, however... why the std::string variable is ok and the casting is not ok ? – quinzio Jan 29 '20 at 08:55
  • Fine. I start to see the light... looking here https://en.cppreference.com/w/cpp/regex/regex_search at point 7) ----- 7) The overload 3 is prohibited from accepting temporary strings, otherwise this function populates match_results m with string iterators that become invalid immediately.---- So the problem is the temporary variable. The casting produces a temporary variable, instead the "named" variable is not temporary. OK, thank to all for the support. – quinzio Jan 29 '20 at 08:59