gpt4 book ai didi

c++ - C++17 std::filesystem::path 中的 native 路径分隔符错误?

转载 作者:IT老高 更新时间:2023-10-28 22:03:43 24 4
gpt4 key购买 nike

#include <experimental/filesystem> 升级时遇到问题至#include <filesystem> .似乎 std::filesystem::path::wstring方法返回的字符串与 experimental::filesystem 中的字符串不同.我编写了以下包含输出结果的小测试程序。

#include <iostream>
#include <filesystem>
#include <experimental/filesystem>

namespace fs = std::filesystem;
namespace ex = std::experimental::filesystem;
using namespace std;

int main()
{
fs::path p1{ L"C:\\temp/foo" };
wcout << "std::filesystem Native: " << p1.wstring() << " Generic: " << p1.generic_wstring() << endl;

ex::path p2{ L"C:\\temp/foo" };
wcout << "std::experimental::filesystem Native: " << p2.wstring() << " Generic: " << p2.generic_wstring() << endl;
}

/* Output:
std::filesystem Native: C:\temp/foo Generic: C:/temp/foo
std::experimental::filesystem Native: C:\temp\foo Generic: C:/temp/foo
*/

根据https://en.cppreference.com/w/cpp/filesystem/path/string :

Return value

The internal pathname in native pathname format, converted to specified string type.

该程序在 Windows 10 上运行,并使用 Visual Studio 2017 版本 15.8.0 编译。我希望 native 路径名是 C:\temp\foo .

问题:这是 std::filesystem::path 中的错误吗? ?

最佳答案

大致而言,当编译器出现标准禁止的行为(显式或隐式)或与所述编译器的文档不同的行为时,就会发生错误。

该标准对本地路径字符串的格式没有任何限制,只是底层操作系统应该接受该格式(以下引用)。它怎么能施加这样的限制?该语言对主机操作系统如何处理路径没有发言权,并且要自信地做到这一点,它必须知道它可能编译到的每一个目标,这显然是不可行的。

[fs.class.path]

5   A pathname is a character string that represents the name of a path. Pathnames are formatted according to the generic pathname format grammar ([fs.path.generic]) or according to an operating system dependent native pathname format accepted by the host operating system.

(强调我的)

The documentation of MSVC暗示正斜杠完全可以用作分隔符:

Common to both systems is the structure imposed on a pathname once you get past the root name. For the pathname c:/abc/xyz/def.ext:

  • The root name is c:.
  • The root directory is /.
  • The root path is c:/.
  • The relative path is abc/xyz/def.ext.
  • The parent path is c:/abc/xyz.
  • The filename is def.ext.
  • The stem is def.
  • The extension is .ext.

它确实提到了首选分隔符,但这实际上仅暗示 std::make_preferred 的行为,而不是默认路径输出的行为:

A minor difference is the preferred separator, between the sequence of directories in a pathname. Both operating systems let you write a forward slash /, but in some contexts Windows prefers a backslash \.

因此,这是否是错误的问题很简单:由于标准对行为没有施加任何限制,并且编译器的文档暗示没有强制需要反斜杠,因此不可能有错误。

剩下的问题是这是否是一个实现质量问题。毕竟,编译器和库的实现者应该知道他们的目标的所有怪癖,并相应地实现特性。

您应该在 Windows 中使用哪个斜杠('\''/'),或者它是否真的很重要,有待商榷,所以可以没有权威的答案。任何主张其中一个或另一个的答案都必须非常小心,不要过于基于意见。此外,path::make_preferred 的存在表明 native 路径不一定是首选路径。考虑零开销原则:让路径始终是首选路径会给那些在处理路径时不需要那么迂腐的人带来开销。

最后,std::experimental 命名空间就是它在包装盒上所说的:你不应该期望最终标准化库的行为与其实验版本相同,或者甚至期望最终标准化图书馆将完全存在。处理实验性的东西时就是这样。

关于c++ - C++17 std::filesystem::path 中的 native 路径分隔符错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51886072/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com