Qt: QString constant in a class

A constant QString can be achieved by defining the macro


#CONSTSTRING "-_-"

and by creating a temporary QString instance in each place the constant is needed e.g. for a window title.


...
window.setWindowTitle(QString(CONSTSTRING));
...

A lot of the Qt goodness is due to macros but most of them are defined as empty for good reason. Macros are processed by a preprocessor which replaces the macro by the given text in the source file before the compiler knows what happens. Amongst others they can produce unplanned side-effects due to the missing data type and thus in Qt they are mainly used as markers for the Meta-Object-Compiler.

Another drawback is that if the constant is used in numerous places, numerous of anonymous, unnamed variables are created which reduces the efficiency.

All these drawbacks can be avoided by simply defining a static constant as shown in the following example. In myclass.h the constant is defined …


class MyClass
{
private:
  static const QString constString;
}

… and initialized in myclass.cpp


#include "MyClass.h"

const QString MyClass::constString = QString("-_-");

The assignment of const QStrings are also faster thanks to implicit sharing of QString because the first example doesn’t use implicit shared objects and thus they can’t be shallow copied.

If this global constant QString is used in other modules too then it can happen that your program crashes because of the static initialization order fiasco which should always be avoided because such errors are hard to find.

To not run into any trouble in that case use the construct on first use idiom [1, 2], where you simply wrap your static object inside a function.


const QString & constantQString()
{
  static const QString constant("-_-");
  return constant;
}

2 Comments

  1. Yash

    Thanks :)

  2. a

    Hurrah! After all I got a blog from where I be able to actually get useful facts regarding my study
    and knowledge.

Leave a Reply

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

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>