regex_match 个访问和不访问已删除函数的案例

regex_match cases that do & don't access deleted function

我试图理解为什么我的一行代码以一种方式编译而另一行以另一种方式编译。

我无法将 direntry.path().wstring() 直接传递给 regex_match 而不会出现“试图引用已删除的函数”构建错误。

const std::wstring directoryPath; // function parameter
for (auto& direntry : std::filesystem::directory_iterator(directoryPath))
{
    std::wsmatch fileMatches;
    if (direntry.is_regular_file()
        // Get "attempting to reference a deleted function" on the next line
        && std::regex_match(direntry.path().wstring(), fileMatches, *m_pRegexFile)
        && fileMatches.size() >= 2)
    {
        ...
    }

如果我添加 filePath 变量,同样的事情编译正常。

const std::wstring directoryPath; // function parameter
for (auto& direntry : std::filesystem::directory_iterator(directoryPath))
{
    std::wsmatch fileMatches;
    std::wstring filePath = direntry.path().wstring();
    if (direntry.is_regular_file()
        && std::regex_match(filePath, fileMatches, *m_pRegexFile)
        && fileMatches.size() >= 2)
    {
        ...
    }

与此同时,它按原样工作得很好。

std::wregex regexSubdirectory(L"cam.*", std::regex::icase);
for (auto& direntry : std::filesystem::directory_iterator(baseFolder.c_str()))
{
    if (direntry.is_directory()
        && std::regex_match(direntry.path().wstring(), regexSubdirectory))
    {
        ...
    }
}

我的代码正在编译,但我不喜欢神秘。为什么一个编译时没有变量而另一个需要它?据我所知,一个可能在后台传递 const CharT*,而另一个在传递 const std::basic_string&。但是...我对定义 (https://en.cppreference.com/w/cpp/regex/regex_match) 摸不着头脑,而且我 认为 他们应该传递相同的东西。有什么想法吗?

查看该 cppreference 页面上列表中的 #7。 采用右值 basic_string 的调用被标记为已删除。

在您的第一次调用中,您传递了一个临时字符串。 (右值)

在你的第二次调用中,你传递了一个左值。

[稍后] 删除该调用的原因是为了防止编程错误。考虑示例中的以下代码:

std::regex_match(direntry.path().wstring(), fileMatches, *m_pRegexFile);

当此 returns 时,fileMatches 将一堆迭代器包含到它匹配的字符串中。但是,字符串是临时的,一旦regex_matchreturns就会被销毁。现在访问 fileMatches 中的任何匹配项都将是未定义的行为 - 并且可能会崩溃。