如何解决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_path
和 test_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 举报,一经查实,本站将立刻删除。