代码之家  ›  专栏  ›  技术社区  ›  Wyck

试图引用已删除函数的正则表达式\u令牌\u迭代器

  •  0
  • Wyck  · 技术社区  · 7 年前

    我试图用C++中的正则表达式来分割字符串。以下是最低要求:

    #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);
    }
    

    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
    

    但我觉得我的设置是正确的。为什么我会遇到这个错误?我需要做什么更改才能编译它?

    this gist 作为一个例子,但是我也不能编译它。

    我正在使用Microsoft Visual Studio 2017 15.8.4进行构建

    1 回复  |  直到 7 年前
        1
  •  3
  •   rafix07    7 年前

    构造函数 regex 因为临时对象被删除,因为 迭代器不复制 正则表达式 但是保持对这个对象的引用。 防止将临时变量传递到迭代器中 .

    根据 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;
    

    因此,您需要做的是将regex创建为 L值

      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);
    

    const regex_type& re -所以可以将regex的临时对象传递给迭代器的ctor,但它会导致 .