From 8379d1e90a3296b3be961878ee31f93ec672f883 Mon Sep 17 00:00:00 2001 From: Thiago Macieira Date: Mon, 27 Jan 2025 12:18:45 -0800 Subject: [PATCH] QFile: refactor {to,from}FilesystemPath to avoid temporary allocations Avoiding #ifdef and reinterpret_cast too, to boot. It was already the case on Windows and for fromFilesystemPath everywhere, but now we can also benefit from the QString::toStdString() that also avoids a temporary. Change-Id: Ie4f0a129d0f2f3653046fffd2ec22713a5516ada Reviewed-by: Ahmad Samir --- src/corelib/io/qfile.h | 16 +++++++++------- 1 file changed, 9 insertions(+), 7 deletions(-) diff --git a/src/corelib/io/qfile.h b/src/corelib/io/qfile.h index c6caf5c56e3..c115a6aee98 100644 --- a/src/corelib/io/qfile.h +++ b/src/corelib/io/qfile.h @@ -58,17 +58,19 @@ public: namespace QtPrivate { inline QString fromFilesystemPath(const std::filesystem::path &path) { -#ifdef Q_OS_WIN - return QString::fromStdWString(path.native()); -#else - return QString::fromStdString(path.native()); -#endif + // we could use QAnyStringView, but this allows us to statically determine + // the correct toString() call + using View = std::conditional_t; + return View(path.native()).toString(); } inline std::filesystem::path toFilesystemPath(const QString &path) { - return std::filesystem::path(reinterpret_cast(path.cbegin()), - reinterpret_cast(path.cend())); + if constexpr (sizeof(std::filesystem::path::value_type) == sizeof(char16_t)) + return std::u16string_view(QStringView(path)); + else + return path.toStdString(); } // Both std::filesystem::path and QString (without QT_NO_CAST_FROM_ASCII) can be implicitly