c++ - 为什么 boost::filesystem::path::string() 在 Windows 上按值返回,而在 POSIX 上按引用返回?

标签 c++ boost boost-filesystem

来自 boost/filesystem/path.hpp:

#   ifdef BOOST_WINDOWS_API
    const std::string string() const
    {
      [...]
    }
#   else   // BOOST_POSIX_API
    //  string_type is std::string, so there is no conversion
    const std::string&  string() const { return m_pathname; }
    [...]
#   endif

对于 wstring() 来说恰恰相反——在 Windows 上通过引用返回,在 POSIX 上通过值返回。这有什么有趣的原因吗?

最佳答案

在 Windows 上,path 存储一个 wstring,因为在 Windows 中处理 Unicode 编码路径的唯一方法是使用 UTF-16。在其他平台上,文件系统通过 UTF-8(或足够接近)处理 Unicode,因此在这些平台上,path 存储一个 string

因此在非 Windows 平台上,path::string 将返回对实际内部数据结构的常量引用。在 Windows 上,它必须生成一个 std::string,因此它通过复制返回它。

请注意 File System TS绑定(bind)到 C++17 不会这样做。在那里,path::string 将始终返回一个拷贝。如果您想要 native 存储的字符串类型,则必须使用 path::native,其类型将取决于平台。

关于c++ - 为什么 boost::filesystem::path::string() 在 Windows 上按值返回,而在 POSIX 上按引用返回?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37529670/

相关文章:

c++ - 如何确保 boost::filesystem::remove 不会尝试删除另一个进程使用的文件?

c++ - 在同一个函数/程序中使用 WebSocket++ 服务器和客户端

c++ - 有没有一种标准方法可以在不使用 Boost 的情况下将 std::string 转换为 std::chrono::time_point?

c++ - 如何在运行时正确地将指向派生类的 void* 转换为指向基类的 void*

c++ - C++ 中是否有任何方法可以执行 round(a, n) ?

STL 或 boost 中的 C++ range/xrange 等价物?

c++ - 如果需要,如何使用 Boost 库将具有可变数量参数的处理程序传递给类

c++ - 从 Visual Studio 2008 切换到 Visual Studio 2010,现在无法链接到 boost 文件系统

c++ - 为 char 数组添加 Boost 文件系统路径

c++ - 使用 C++ 线程/boost 线程的有效方法