[Development] A QStringList puzzle for Monday
Marc Mutz
marc.mutz at qt.io
Tue Mar 18 07:12:29 CET 2025
On 17.03.25 20:09, Jøger Hansegård via Development wrote:
[...]
> I agree that it would be nice to have a compiler error but given that QStringList behaves the same way as std::vector, I am not sure it is a bug.
For the specific case of QList, we could take first and last by
reference, preventing the decay of the argument to pointers, and thus to
something that looks like iterators. But that's shotgun surgery.
Everywhere else (incl. STL) iterators are passed by value, and make
arguments decay.
The solution, as others have pointed out, is simple: don't use C string
literals to initialize QStrings. Define QT_NO_CAST_FROM_ASCII (and
_TO_ASCII, _FROM_BYTEARRAY, to fix two other gotchas), and use
Qt::StringLiteral UDLs, which make QT_NO_CAST_FROM_ASCII bearable for
the first time in Qt's history.
Also, get into the habit of using {} instead of () unless you need to
tie-break between an initializer_list constructor and
non-initializer_list one. It also prevents narrowing.
Daunting for an existing project to implement, but trivial if you just
start out.
The action point for Qt itself is to avoid APIs that depend too much on
implicit conversion and overloading. Prefer named constructors
(QList::fromRange), and explicit function names
(appendString()/appendByteArray() instead of
append(QString)/append(QByteArray)). Make ctors and conversion operator explicit.
Thanks,
Marc
--
Marc Mutz <marc.mutz at qt.io> (he/his)
Principal Software Engineer
The Qt Company
Erich-Thilo-Str. 10 12489
Berlin, Germany
www.qt.io
Geschäftsführer: Mika Pälsi, Juha Varelius, Jouni Lintunen
Sitz der Gesellschaft: Berlin,
Registergericht: Amtsgericht Charlottenburg,
HRB 144331 B
More information about the Development
mailing list