QUrl (mis)usage: appendix, avoid automatic cast from QString

As I was introducing in the former entry QUrl (mis)usage, the direct creation of a QUrl from a QString should be avoided in any software that is not trying to smartly guess what a user input should lead to.

So, going directly to the ham, to avoid mistakes due to automatic conversions from QString to QUrl, I encourage the usage of the QT_NO_URL_CAST_FROM_STRING macro. The only thing you have to do is adding a line to your qmake project file like this:

# Avoid automatic casts from QString to QUrl. Dangerous!!!
DEFINES += QT_NO_URL_CAST_FROM_STRING

Or add it directly to the compilation line, like this

g++ ... -DQT_NO_URL_CAST_FROM_STRING ...

As I was pointing in my previous post, the usage of QUrl::fromLocalFile(QString) and QUrl::fromEncoded(QByteArray, QUrl::StrictMode) is recommended when dealing with QString and QUrl, but committing mistakes is a human condition so it is pretty easy to end passing a QString as a parameter to some API expecting a QUrl, or assigning a QString to a QUrl with the «=» operator through the C++ automatic cast mechanism which is implemented in the QUrl class. That’s why forbidding these automatic casts in our code is of such importantance.

Deja una respuesta

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *