0

I'm trying to understand the behavior of the following code.

I think it might be a bug since the result looks wrong to me.

#include <iostream>
#include <regex>

int main(int ac, char **av)
{
  std::regex reg("lib(.*)\\.so");
  std::smatch match;
  std::cout << std::regex_match(std::string("libscio.so"), match, reg) << std::endl;
  std::cout << match.str(1) << std::endl;

  return 0;
}

I'm expecting

1
scio

But it gives me

1
ocio

Compiled with gcc version 4.9.2 (Debian 4.9.2-10) on x86_64 GNU/Linux

  • 5
    Maybe something to do with [this](http://stackoverflow.com/questions/33154890/simple-stdregex-search-code-wont-compile-with-apple-clang-std-c14)? – LogicStuff Jul 05 '16 at 13:42
  • 2
    Which Standard version did you compile as? As noted in @LogicStuff's link which answers this, passing a _rvalue_ was UB in C++11 and for that reason is now forbidden in C++14. – underscore_d Jul 05 '16 at 13:48

1 Answers1

2

I had to structure the program differently because it would not compile otherwise in VS 2015. Maybe that's causing your problem, with your compiler, too? Note the string temporary variable.

#include <iostream>
#include <regex>

int main(int ac, char **av)
{
  std::regex reg("lib(.*)\\.so");
  std::smatch match;
  std::string target = "libscio.so";
  std::cout << std::regex_match(target, match, reg) << std::endl;
  std::cout << match.str(1) << std::endl;

  return 0;
}

This yields 1 and scio in VS 2015 as expected.

According to the link @LogicStuff posted, this is because passing in a temporary object means that the matches point to iterators that are invalidated when the temporary goes out of scope. So what you see probably is the garbage left over when your temporary string got deleted.

Community
  • 1
  • 1
nvoigt
  • 75,013
  • 26
  • 93
  • 142