Create QString with QStringLiteral and arg
-
Hi
It does seems to workWith QStringLiteral it makes a QStaticStringData
else not. -
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.
-
Hi
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("%1/%2/%3")
is "aQStringLiteral
" (sort of), once you goQStringLiteral("%1/%2/%3").arg(...)
then what you get back is aQString
, as per e.g. http://doc.qt.io/qt-5/qstring.html#arg?
-
@mrjj
I believe:"%1/%2/%3"
=> read-only/literal stringQStringLiteral("%1/%2/%3")
=> read-only/literal stringQStringLiteral("%1/%2/%3").arg(...)
=> functionQString::arg()
returns a plainQString
=> whatever rules forQString
only, not per se read-only/literal string
That's the point --- it's the use of the
arg()
function that changes the "type". -
QStringLiteral
will construct aQString
object once in the program lifetime from theconst char *
you pass it. This is happening through a bit of static initialization magic. After that you can use thatQString
object wherever you feel like it. The idea is that shallow copies ofQString
(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.