QString::null WTF!

I recently discovered the cause of a bug feature in some software that I wrote (Qt 3.3.8) and thought that I’d share the information since it feels like the sort of thing that lots of people might have done. Essentially, the problem was my assumption that QString::null is some sort of special value, it isn’t, it is just a reference to a static empty QString. Given this information, consider the following three QStringLists:

QStringList listOne = QStringList();
QStringList listTwo = QStringList( QString::null );
QStringList listThree = QStringList( "" );

If, like me, you assumed that QString::null was a special null value, then you might reasonably expect both listOne and listTwo to be empty QStringLists and listThree a QStringList containing a single empty QString. The reality is that listTwo is actually equivalent to listThree, so when you are tearing your hair out trying to work out why your nice empty QStringList has a length of 1, remember this post. You have been warned.

It is worth noting that QString::null has been deprecated as of Qt4.0 and calls to it now evaluate to seperate calls to QString(), I guess I wasn’t the only person that fell into this trap! I know that assumption is the Mother of all fuck ups, but I can’t help thinking that this could have all been avoided by naming it QString::empty instead.

2 thoughts on “QString::null WTF!

  1. Ooer. They’re right to deprecate it, that’s pretty horrible. “” is eleven less characters to type than QString::null too!

    At the risk of sounding like a spoilt child, Rails has added a nice extension to many of Ruby’s types called ‘blank?’, which evaluates true for ‘nil’ (semantically like a null pointer in C/C++), empty strings and strings containing only whitespace, empty arrays and empty hashes. In many cases, you’re not interested if a string or array is empty or nil (i.e. not a string/array at all), as semantically it amounts to the same thing, hence a single test function ‘blank?’.

    I would suggest you add an isBlank() function to QString (and QList etc), but alas, you can only do that by derivation in C++ so all your uses of QString would have to change to QString2 or some such (namespaces in C++ are open, but classes are closed). Also, there is no C++ class equivalent to Ruby’s ‘nil’, so you wouldn’t be able to add the ‘isBlank()’ method to that (which is the main benefit of ‘blank?’ really).

  2. @Chris: ‘blank?’ sounds like what I thought QString::null was. Again, the choice to use C++ was not mine, but not necessarily one that I disagree with given the purpose of the application and its target audience.

Leave a Reply

Your email address will not be published. Required fields are marked *