std::filesystem::path parent_path() 返回错误结果

问题描述

std::filesystem::path parent_path() 在某些情况下可能会重新命名。 简化代码如下:

#include<filesystem>
#include<iostream>

std::string get_str() {
    static std::string str = "/a/b/c/d/e/f/g/h";
    return str;
}
int main() {
      std::filesystem::path test_path(get_str());
      std::cout << "test_path: " << test_path << std::endl;
      std::cout << "test_path.parent_path(): " << test_path.parent_path() << std::endl;
      std::cout << "test_path.parent_path().parent_path().parent_path().parent_path(): " << test_path.parent_path().parent_path().parent_path().parent_path() << std::endl;
}

如果使用 clang-10 clang++ -std=c++17 test.cpp 或 gcc-10 g++ -std=c++17 test.cpp 编译,则返回:

test_path: "/a/b/c/d/e/f/g/h"
test_path.parent_path(): "/a/b/c/d/e/f/g/h"
test_path.parent_path().parent_path().parent_path().parent_path(): "/a/b/c/d/e"

test_pathtest_path.parent_path() 是一样的,但其余的 parent_path() 是正确的,这真的很奇怪

但是如果我删除函数 static 中的 get_str,它将返回正确的 parent_path

test_path: "/a/b/c/d/e/f/g/h"
test_path.parent_path(): "/a/b/c/d/e/f/g"
test_path.parent_path().parent_path().parent_path().parent_path(): "/a/b/c/d"

另外,如果我把编译参数改成clang++ -std=c++17 -stdlib=libc++ test.cpp,也可以避免这个错误


这是 gcc https://gcc.gnu.org/bugzilla/show_bug.cgi?id=99805一个错误

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)