0 is ambiguous

Posted on

Since Qt 4.7, the QString class has gained a constructor. It used to have QString(const char *), QString(const QChar *, int) and a bunch of others. Now it has QString(const QChar *) as well. This constructor works with 0-terminated QChar sequences, like char * does. A useful addition, except that it makes certain other code constructions newly ambiguous.

Consider code that uses 0 as a pointer; this is now ambiguous because that might be a const char * or a const QChar *. There’s code in KDE where 0 is used in places for QStrings, and this used to work, like class A { public: A() : a(0) {} ; QString a; } ; You don’t always see it that obviously; for instance, there’s arrays of structs with a terminating null struct — a real C-ism. It becomes ambiguous with a QString member: struct { int, int, QString } foo[] = { …, { 0,0,0 } } . For some reason we hit these more clearly in Solaris (OpenIndiana, that is), and we’ve started to fix them. The simple fix is to use QString() to mean an empty string (QString::null? damn I’m oldschool).

One more reason to look forward to nullptr (didn’t mpyne or MarcM mention that recently?).

7 Comment(s)

  1. Euh as far I know. nullptr will work to make a difference between:
    void func(int);
    void func(char*);

    func(0);

    But I fail to see how it would solve:
    void func(QChar*);
    void func(char*);

    func(nullptr);

    1. @cyrille: you’re right there. But the use of nullptr instead of 0 might make folks think a little harder about what kind of nullptr that is — or consider that writing QString() is only 2 characters more.

  2. iirc QString() should be preferred over QString(0) or QString(“”) anyway – the ctor QString() is declared inline and defined in qstring.h whereas QString(const QChar* unicode)’s body lies in qstring.cpp with an if(!unicode) – i know it’s not much difference but it is a difference 😉

  3. @cptG: The QString() ctor shallow-copies the shared null instance of QString::Data. This basically means copying the QString::Data pointer and increasing the atomic reference counter.

    On the other hand, QString(“”) constructs a new QStringData instance (pointing to an empty QChar array) which is far more expensive.

  4. adridg, there’s “NULL” already, which can be defined using some compiler-extension like “__null”, so there is (read: I see no) reason for “nullptr”, especially since it fails to solve the problem.

    Also note, that in case of NULL-terminating an array, empty braces are enough.

  5. Pingback: mina86.com

Comments are closed.