gpt4 book ai didi

c++ - 带 string_view 的正则表达式返回垃圾

转载 作者:行者123 更新时间:2023-12-05 03:23:38 29 4
gpt4 key购买 nike

std::string_view 上匹配正则表达式工作正常。但是当我返回匹配的子字符串时,它们会因为某种原因而消失。 std::string_view 参数在函数作用域结束时被销毁,但它指向的内存是有效的。
我希望 std::match_results 指向初始数组而不进行任何复制,但我观察到的行为表明我错了。是否可以在不为子字符串额外分配的情况下使该函数工作?

#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 &regexStr =
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 显示警告:支持指针的对象将在完整表达式的末尾被销毁std::string_view platform = matchResults[2].str();

最佳答案

例如,让我们看一下下面这行:

std::string_view config = matchResults[1].str();

这里,matchResults 的类型是 std::match_results , [1] 是它的 std::match_results::operator[] ,它返回一个 std::sub_match .

但是,.str() 是它的 std::sub_match::str() ,它返回一个 std::basic_string

这个返回的临时 sting 对象将在完整表达式的末尾被销毁(感谢@BenVoigt 的更正),即在这种情况下,在 config 被初始化和有问题的行完成执行。因此,您引用的 Clang 警告是正确的。

parse_condition_str() 函数返回时,configplatform 字符串 View 将因此指向已经被销毁的字符串。

关于c++ - 带 string_view 的正则表达式返回垃圾,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72467734/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com