在 a 上匹配正则表达式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 ®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;
}
Run Code Online (Sandbox Code Playgroud)
https://godbolt.org/z/TeYMnn56z
CLang-tydy 显示警告:支持指针的对象将在完整表达式末尾被销毁
std::string_view platform = matchResults[2].str();
例如,让我们看一下以下行:
std::string_view config = matchResults[1].str();
Run Code Online (Sandbox Code Playgroud)
这里,matchResults是 类型std::match_results,[1]是其std::match_results::operator[],它返回一个std::sub_match。
但是,.str()它的std::sub_match::str(),它返回一个std::basic_string。
这个返回的临时字符串对象将在完整表达式的末尾被销毁(感谢@BenVoigt的更正),即在这种情况下,在初始化config并且相关行完成执行之后立即销毁。因此,您引用的 Clang 警告是正确的。
当parse_condition_str()函数返回时,config和platform字符串视图都将指向已经被破坏的字符串。
| 归档时间: |
|
| 查看次数: |
2783 次 |
| 最近记录: |