Solved Create QString with QStringLiteral and arg
tham last edited by
Purpose of QStringLiteral is avoid dynamic buffer allocation, but create string with arg do need to know the buffer size at runtime, could I gain any benefits by creating QString by QStringLiteral under this kind of case?
QString const birth = QStringLiteral("%1/%2/%3").arg(year).arg(date).arg(time);
It does seems to work
With QStringLiteral it makes a QStaticStringData
I also tried it and found it worked. My bad.
I remember trying this at some point in the past and found it didn't work (compile error). For this reason I have always been in the habit of using QString instead of QStringLiteral for anything with arguments. From what I understand QStringLiteral is a macro wrapper that makes static text more memory and CPU friendly (it create a QString directly at compile time and not through a constructor from a char pointer) so I always assumed it was specifically aimed at static text.
I also though it would not work as it not very static in nature but it seems
to create this static struct regardless.
But since we alter it a runtime, it cant be in read only memory so there is still something
fishy here :)
I don't see the problem/issue.
https://woboq.com/blog/qstringliteral.html, http://blog.qt.io/blog/2014/06/13/qt-weekly-13-qstringliteral/, https://www.kdab.com/qstringview-diaries-advances-qstringliteral/ may help.
And I assume that while
QStringLiteral" (sort of), once you go
QStringLiteral("%1/%2/%3").arg(...)then what you get back is a
QString, as per e.g. http://doc.qt.io/qt-5/qstring.html#arg
good links. There is nothing wrong but clearly the whole expression cannot be read only so
i guess only "%1/%2/%3" is in readonly section and rest is dynamic.
"%1/%2/%3"=> read-only/literal string
QStringLiteral("%1/%2/%3")=> read-only/literal string
QString::arg()returns a plain
QString=> whatever rules for
QStringonly, not per se read-only/literal string
That's the point --- it's the use of the
arg()function that changes the "type".
tham last edited by
I guess we can say QStringLiteral may offer some small optimization in this case(part of the string could construct at compile time, no dynamic allocation), unless it wouldn't worse than construct by QString directly?
QStringLiteralwill construct a
QStringobject once in the program lifetime from the
const char *you pass it. This is happening through a bit of static initialization magic. After that you can use that
QStringobject wherever you feel like it. The idea is that shallow copies of
QString(due to it having implicit sharing) is very cheap. If you use "write" operations on it the data will be detached, as it's the case here - arg will copy out the literal part to do the replacement. However you'd still get some small optimization for the initial string construction.
Yes, the initial use of
QStringLiteralmay save you at least 1 nanosecond or 10 bytes in your overall program... :)