2

I'm trying to split a string with a regular expression in C++. Here's the minimum repro:

#include <string>
#include <regex>

int main()
{
  std::string str("abc");
  std::string regex("b");
  std::regex_token_iterator<std::string::const_iterator> a(str.begin(), str.end(), std::regex(regex), -1);
}

This program gives me a compile error: attempting to reference a deleted function

error C2280: 'std::regex_token_iterator<std::_String_const_iterator<std::_String_val<std::_Simple_types<_Ty>>>,char,std::regex_traits<char>>::regex_token_iterator(_BidIt,_BidIt,const std::basic_regex<char,std::regex_traits<char>> &&,int,std::regex_constants::match_flag_type)': attempting to reference a deleted function

But I feel like I've set it up correctly. Why am I getting this error and what do I need to change to get it to compile?

I was working from this gist as an example, but I can't get it to compile either.

I'm building with Microsoft Visual Studio 2017 15.8.4

Wyck
  • 10,311
  • 6
  • 39
  • 60

1 Answers1

4

Constructor which takes regex as temporary object is deleted because iterator doesn't make a copy of regex but keeps reference to this object. This deleted function is to prevent from passing temporaries into iterator. If you passed temporary object into iterator, you would get dangling reference.

According to reference:

regex_token_iterator( BidirectionalIterator a, BidirectionalIterator b,
                      const regex_type&& re,
                      int submatch = 0,
                      std::regex_constants::match_flag_type m =
                          std::regex_constants::match_default ) = delete;

so what you need to do is create regex as L-value object:

  std::string str("abc");
  std::string regex("b");
  std::regex r(regex);
  std::regex_token_iterator<std::string::const_iterator> a(
       str.begin(), str.end(), r, -1);

Regarding the link you posted, deleted overload which takes reference to R-value was introduced since C++14, in C++11 there is overload which takes const regex_type& re - so a temporary object of regex can be passed to ctor of iterator, but it leads to undefined behaviour.

rafix07
  • 20,001
  • 3
  • 20
  • 33
  • I would have preferred that "undefined behaviour" was spelled out rather than being written as "UB". I had to go look that up, and [so have others](https://stackoverflow.com/questions/2766731/what-exactly-do-ib-and-ub-mean). – Wyck Dec 04 '18 at 04:03