来自 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/