Qt: QString constant in a class

A constant QString can be achieved by defining the macro


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


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
  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;


  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.

  3. i Acquired lace wigs,bob wigs https://youtu.be/3KO3e4I3_24 in Chestnut. Honestly. They may be tremendous lovable, i’ve gotten PLENTY of compliments, They’re my 4th just one, but to this point the very best types. They’re tremendous nice.

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>