diff options
| author | Thiago Macieira <thiago.macieira@intel.com> | 2025-01-27 14:02:44 -0800 |
|---|---|---|
| committer | Thiago Macieira <thiago.macieira@intel.com> | 2025-02-22 05:17:36 -0800 |
| commit | 3b73bc463db1407096941239170040a2692ecdac (patch) | |
| tree | 3776588bc64abf60c9a70a2956c1c23220d6a877 /src/corelib/text/qstring.cpp | |
| parent | f846754663aae1652e4eec9a441ee222af352319 (diff) | |
QString: de-inline toStdString() so we can avoid a QByteArray temporary
We can simply write the UTF-8 string into the std::string buffer,
bypassing our temporary. And when Qt is compiled with C++23, we even get
resize_and_overwrite() support, removing the unnecessary memset() -
though the compiler might have been smart enough to suppress it (GCC and
Clang currently aren't that smart; in fact, GCC even generates code to
deal with a default-constructed std::string not being empty).
Change-Id: I3883268b30a9065757dcfffd6da4705a4aa44d7a
Reviewed-by: Giuseppe D'Angelo <giuseppe.dangelo@kdab.com>
Diffstat (limited to 'src/corelib/text/qstring.cpp')
| -rw-r--r-- | src/corelib/text/qstring.cpp | 20 |
1 files changed, 20 insertions, 0 deletions
diff --git a/src/corelib/text/qstring.cpp b/src/corelib/text/qstring.cpp index b0b78cd10b0..3e132cf155e 100644 --- a/src/corelib/text/qstring.cpp +++ b/src/corelib/text/qstring.cpp @@ -9374,6 +9374,26 @@ QString::iterator QString::erase(QString::const_iterator first, QString::const_i \sa toLatin1(), toUtf8(), toLocal8Bit(), QByteArray::toStdString() */ +std::string QString::toStdString() const +{ + std::string result; + if (isEmpty()) + return result; + + auto writeToBuffer = [this](char *out, size_t) { + char *last = QUtf8::convertFromUnicode(out, *this); + return last - out; + }; + size_t maxSize = size() * 3; // worst case for UTF-8 +#ifdef __cpp_lib_string_resize_and_overwrite + // C++23 + result.resize_and_overwrite(maxSize, writeToBuffer); +#else + result.resize(maxSize); + result.resize(writeToBuffer(result.data(), result.size())); +#endif + return result; +} /*! \fn QString QString::fromRawData(const char16_t *unicode, qsizetype size) |
