【问题标题】:Inconsistent results from std::regex_search with gcc 4.9.1std::regex_search 与 gcc 4.9.1 的结果不一致
【发布时间】:2014-11-11 14:18:20
【问题描述】:

我从 std::regex_search 得到各种错误结果,似乎取决于程序中的其他代码:

#include <regex>
#include <iostream>

int main(){
  std::smatch res;

  std::regex_search(std::string("fooquxbarquack"),res,std::regex("foo(?=qux)(.*)ar"));
  std::cout<<res[0]<<std::endl;

  std::regex_search(std::string("foofofowoof"),res,std::regex("(o.){4}"));
  std::cout<<res[0]<<std::endl;

  return 0;
}

输出(格式化为 c 字符串):

fooquxba0\n
ofofow\xB0\x00\n

如果我反转测试,输出变为:

ofofow\xD0\x00\n
fooquxbar\n

在代码的其他安排下,它有时会产生预期的输出(fooquxbarofofowoo)。

gcc 版本:

$ ../bin/gcc -v
Using built-in specs.
COLLECT_GCC=../bin/gcc
COLLECT_LTO_WRAPPER=/compilers/gcc_r/4.9.1rh62/libexec/gcc/x86_64-unknown-linux-gnu/4.9.1/lto-wrapper
Target: x86_64-unknown-linux-gnu
Configured with: /free/tmp/gccwork/gcc-4.9.1//configure --prefix=/compilers/gcc_r/4.9.1rh62/
Thread model: posix
gcc version 4.9.1 (GCC) 

【问题讨论】:

    标签: c++ regex gcc c++11


    【解决方案1】:

    您不能调用 regex_searchregex_match 重载,将 match_results 与临时 std::string 结合使用。 (嗯,你可以,C++14 之前的版本,但你不能对结果做任何有用的事情。)

    这些函数将带有迭代器的match_results 填充到您传递的字符串中,但如果您传递一个临时的std::string,那么临时在完整表达式的末尾被销毁,并且迭代器无效。当您稍后尝试使用 res[0] 时,会产生未定义的行为。

    这就是为什么在 C++14 LWG issue 2329 中添加了显式删除的重载以防止它们被临时调用。看起来 libstdc++ 还没有实现这个。您的代码无法在 C++14 模式下使用 clang 和 libc++ 编译。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-10-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-04-09
      相关资源
      最近更新 更多