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

标签 c++ regex c++17

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/

相关文章:

c++ - 使用 C++20 三向比较进行更静默的行为变化

c++ - 为什么不支持串联std::string和std::string_view?

c++ - 带括号的预期的不合格ID错误

c++ - Linux c++错误: undefined reference to 'dlopen'

java - 在大约 100 个字符和下一个符号后分割字符串 (Java)

javascript - 正则表达式来定位一组带有包含和排除的单词的可选列表的单词

python - 正则表达式:仅在花括号内为单词添加引号

c++ - 前向声明 boost.type_erasure 引用类型

c++ - 为什么我的功能没有运行?

c++ - 将对象移到unique_ptr