Matching a regex on a std::string_view
works fine. But when I return matched substrings, they die for some reason. std::string_view
argument is being destroyed upon the end of the function's scope, but the memory it points to is valid.
I expected std::match_results
to point to the initial array and not to make any copies, but the behavior I observe shows that I am wrong.
Is it possible to make this function work without additional allocations for substrings?
#include <tuple>
#include <regex>
#include <string_view>
#include <iostream>
using configuration_str = std::string_view;
using platform_str = std::string_view;
std::tuple<configuration_str, platform_str> parse_condition_str(std::string_view conditionValue)
{
// TODO: fix regex
constexpr const auto ®exStr =
R"((?:\'\$\(Configuration\)\s*\|\s*\$\(Platform\)\s*\'==\'\s*)(.+)\|(.+)')";
static std::regex regex{ regexStr };
std::match_results<typename decltype(conditionValue)::const_iterator> matchResults{};
bool matched =
std::regex_match(conditionValue.cbegin(), conditionValue.cend(), matchResults, regex);
(void)matched;
std::string_view config = matchResults[1].str();
std::string_view platform = matchResults[2].str();
return { config, platform };
}
int main()
{
const auto &stringLiteralThatIsALIVE = "'$(Configuration)|$(Platform)'=='Release|x64'";
const auto&[config, platform] = parse_condition_str(stringLiteralThatIsALIVE);
std::cout << "config: " << config << "\nplatform: " << platform << std::endl;
return 0;
}
https://godbolt.org/z/TeYMnn56z
CLang-tydy shows a warning: Object backing the pointer will be destroyed at the end of the full expression
std::string_view platform = matchResults[2].str();
std::string
you are viewing is gone at the end of the function.std::string
, there's a view to a string literal (in the example). In the actual code it points to astd::string
that is alive whenparse_condition_str
returnsmatchResults[1].str();
-- Does this return a view or a separate string object? It returns astd::string_type
not a view, in other words a whole different object that represents the data.std::string_view config = matchResults[1].str();
. Here,matchResults
is of typestd::match_results<…>
, and[1]
is itsoperator []
, which returns astd::sub_match
. But then, its.str()
is returning astd::basic_string
, seestd::sub_match<…>::str()
. This returned sting will be destroyed at the end of theparse_condition_str()
function.