【问题标题】:Why does boost::filesystem::path::string() return by value on Windows and by reference on POSIX?为什么 boost::filesystem::path::string() 在 Windows 上按值返回,在 POSIX 上按引用返回?
【发布时间】:2016-09-28 12:28:45
【问题描述】:

来自 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 上按值返回。这有什么有趣的原因吗?

【问题讨论】:

    标签: c++ boost boost-filesystem


    【解决方案1】:

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

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

    请注意,绑定到 C++17 的 File System TS 不会执行此操作。在那里,path::string 将始终返回一个副本。如果您想要本机存储的字符串类型,则必须使用path::native,其类型将取决于平台。

    【讨论】:

      【解决方案2】:

      对于 Windows API,它按值返回,因为变量“m_pathname”需要转换为由“path_traits”实现的不同格式(字符串)。这引入了一个临时变量,当然不能通过引用传递,尽管额外的副本会被 NRVO 或隐式移动忽略。

      对于 posix 情况,'m_pathname' 的格式已经是原生格式(字符串),因此无需转换,因此可以作为 const 引用传递。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-05-19
        • 2023-04-10
        • 1970-01-01
        • 1970-01-01
        • 2019-05-16
        • 1970-01-01
        • 2018-01-16
        • 2018-07-29
        相关资源
        最近更新 更多