Table of Content- Qt Coding Conventions
C++ features
- Don’t use exceptions
- Don’t use rtti (Run-Time Type Information; that is, the
typeinfo
struct, thedynamic_cast
or thetypeid
operators, including throwing exceptions) - Use templates wisely, not just because you can.
Hint: Use the compile
autotest to see whether a C++ feature is supported by all compilers in the test farm.
Conventions in Qt source code
- All code is ascii only (7-bit characters only, run
man ascii
if unsure)- Rationale: We have too many locales inhouse and an unhealthy mix of UTF-8 and latin1 systems. Usually, characters > 127 can be broken without you even knowing by clickingSAVE in your favourite editor.
- For strings: Use
\nnn
(wherennn
is the octal representation of whatever character encoding you want your string in) or\xnn
(wherenn
is hexadecimal). Example:QString s = QString::fromUtf8(”\213\005”);
- For umlauts in documentation, or other non-ASCII characters, either use qdoc’s \unicode command or use the relevant macro; e.g. \uuml for ü
- Every QObject subclass must have a
Q_OBJECT
macro, even if it doesn’t have signals or slots, otherwiseqobject_cast
will fail. - Normalize the arguments for signals + slots (see
QMetaObject::normalizedSignature
) inside connect statements to get faster signal/slot lookups. You can use$QTDIR/util/normalize
to normalize existing code.
Including headers
- In public header files, always use this form to include Qt headers:
#include <QtCore/qwhatever.h>
. The library prefix is neccessary for Mac OS X frameworks and is very convenient for non-qmake projects. - In source files, include specialized headers first, then generic headers.
-
#include <qstring.h> // Qt class
-
#include <new> // STL stuff
-
#include <limits.h> // system stuff
- If you need to include
qplatformdefs.h
, always include it as thefirst header file. - If you need to include
qt_x11_p.h
, always include it as the last header file.
Casting
- Avoid C casts, prefer C++ casts (
static_cast
,const_cast
,reinterpret_cast
)- Rationale: Both reinterpret_cast and C-style casts are dangerous, but at least reinterpret_cast won’t remove the const modifier
- Don’t use
dynamic_cast
, useqobject_cast
for QObjects or refactor your design, for example by introducing a type() method (see QListWidgetItem) - Use the constructor to cast simple types:
int(myFloat)
instead of(int)myFloat
- Rationale: When refactoring code, the compiler will instantly let you know if the cast would become dangerous.
Compiler/Platform specific issues
- Be extremely careful when using the questionmark operator. If the returned types aren’t identical, some compilers generate code that crashes at runtime (you won’t even get a compiler warning).
-
QString s ;
-
return condition ? s : "nothing" ; // crash at runtime - QString vs. const char *
- Be extremely careful about alignment.
- Whenever a pointer is cast such that the required alignment of the target is increased, the resulting code might crash at runtime on some architectures. For example, if a
const char *
is cast to anconst int *
, it’ll crash on machines where integers have to be aligned at a two- or four-byte boundaries. - Use a union to force the compiler to align variables correctly. In the example below, you can be sure that all instances of
AlignHelper
are aligned at integer-boundaries.
- Whenever a pointer is cast such that the required alignment of the target is increased, the resulting code might crash at runtime on some architectures. For example, if a
-
union AlignHelper {
-
char c ;
-
int i ;
-
} ;
- Anything that has a constructor or needs to run code to be initialized cannot be used as global object in library code, since it is undefined when that constructor/code will be run (on first usage, on library load, before main() or not at all). Even if the execution time of the initializer is defined for shared libraries, you’ll get into trouble when moving that code in a plugin or if the library is compiled statically:
-
// global scope
-
static const int i = foo ( ) ; // wrong - call time of foo() undefined, might not be called at all
Things you can do:
-
// global scope
-
static const char x [ ] = "someText" ; // Works - no constructor must be run, x set at compile time
-
static int y = 7 ; // Works - y will be set at compile time
-
static MyStruct s = { 1 , 2 , 3 } ; // Works - will be initialized statically, no code being run
-
static QString *ptr = 0 ; // Pointers to objects are ok - no code needed to be run to initialize ptr
Use Q_GLOBAL_STATIC
to create static global objects instead:
-
-
void foo ( )
-
{
-
s ( ) -> append ( "moo" ) ;
-
}
Note: Static objects in a scope are no problem, the constructor will be run the first time the scope is entered. The code is not reentrant, though.
- A
char
is signed or unsigned dependent on the architecture. Usesigned char
oruchar
if you explicitely want a signed/unsigned char. The following code will break on ppc, for example:
-
char c = 'A' ;
-
if (c < 0 ) { ... } // WRONG - condition is always true on platforms where the default is unsigned char
- Avoid 64-bit enum values.
- The aapcs embedded ABI hard codes all enum values to a 32-bit integer.
- Microsoft compilers don’t support 64-bit enum values. (confirmed with Microsoft ® C/C++ Optimizing Compiler Version 15.00.30729.01 for x64)
Aesthetics
- Prefer enums to define constants over
static const int
or defines.- enum values will be replaced by the compiler at compile time, resulting in faster code
- defines are not namespace safe (and look ugly)
- Prefer verbose argument names in headers.
- Most IDEs will show the argument names in their completion-box.
- It will look better in the documentation
- Bad style:
doSomething(QRegion rgn, QPoint p)
– usedoSomething(QRegion clientRegion, QPoint gravitySource)
instead
Things to avoid
- Do not inherit from template/tool classes
- The destructors are not virtual, leading to potential memory leaks
- The symbols are not exported (and mostly inline), leading to interesting symbol clashes.
- Example: Library A has
class Q_EXPORT X: public QList<QVariant> {};
and library B hasclass Q_EXPORT Y: public QList<QVariant> {};
. Suddenly, QList<QVariant>‘s symbols are exported from two libraries – /clash/.
- Don’t mix const and non-const iterators. This will silently crash on broken compilers.
-
for (Container :: const_iterator it = c. begin ( ) ; it != c. end ( ) ; ++it ) // W R O N G
-
for (Container :: const_iterator it = c. constBegin ( ) ; it != c. constEnd ( ) ; ++it ) // Right
- Q[Core]Application is a singleton class. There can only be one instance at a time. However, that instance can be destroyed and a new one can be created, which is likely in an <nop>ActiveQt or browser plugin. Code like this will easily break:
-
if ( !obj )
If the QCoreApplication
application is destroyed, obj
will be a dangling pointer. UseQ_GLOBAL_STATIC
for static global objects orqAddPostRoutine
to clean up.
- Avoid the use of anonymous namespaces in favor of the static keyword if possible. A name localized to the compilation unit with
static
is guaranteed to have internal linkage. For names declared in anonymous namespaces the C++ standard unfortunately mandates external linkage. (7.1.1/6, or see various discussions about this on the gcc mailing lists)
Binary and Source Compatibility
- Definitions:
- Qt 4.0.0 is a major release, Qt 4.1.0 is a minor release, Qt 4.1.1 is a patch release
- Backward binary compatibility: Code linked to an earlier version of the library keeps working
- Forward binary compatibility: Code linked to a newer version of the library works with an older library
- Source code compatibility: Code compiles without modification
- Keep backward binary compatibility + backward source code compatibility in minor releases
- Keep backward and forward binary compatibility + forward and backward source code compatibility in patch releases
- Don’t add/remove any public API (e.g. global functions, public/protected/private methods)
- Don’t reimplement methods (not even inlines, nor protected/private methods)
- Check Binary Compatibility Workarounds for ways to keep b/c
- Info on binary compatibility: http://techbase.kde.org/Policies/Binary_Compatibility_Issues_With_C++
- When writing a QWidget subclass, always reimplement event(), even if it’s empty. This makes sure that the widget can be fixed without breaking binary compatibility.
- All exported functions from Qt must start with either ‘q’ or ‘Q’. Use the “symbols” autotest to find violations.
Namespacing
- Read Qt in Namespace and keep in mind that all of Qt except Tests and Webkit is “namespaced” code.
Conventions for public header files
Our public header files have to survive the strict settings of some of our users. All installed headers have to follow these rules:
- No C style casts (
-Wold-style-cast
)- Use static_cast, const_cast or reinterpret_cast
- for basic types, use the constructor form: int(a) instead of (int)a
- See chapter “Casting” for more info
- No float comparisons (
-Wfloat-equal
)- Use qFuzzyCompare to compare values with a delta
- Use qIsNull to check whether a float is binary 0, instead of comparing it to 0.0.
- Don’t hide virtual methods in subclasses (
-Woverloaded-virtual
)- If the baseclass
A
has avirtual int val()
and subclassB
an overload with the same name,int val(int x)
,A
‘sval
function is hidden. Use theusing
keyword to make it visible again, and add the following silly workaround for broken compilers:
- If the baseclass
-
class B : public A
-
{
-
#ifdef Q_NO_USING_KEYWORD
-
inline int val ( ) { return A :: val ( ) ; }
-
#else
-
using A :: val ;
-
#endif
-
} ;
-
- Don’t shadow variables (
-Wshadow
)- avoid things like
this->x = x;
- don’t give variables the same name as functions declared in your class
- avoid things like
- Always check whether a preprocessor variable is defined before probing its value (
-Wundef
)
-
#if Foo == 0 // W R O N G
-
#if defined(Foo) && Foo == 0 // Right
-
#if Foo - 0 == 0 // Clever, are we? Use the one above instead, for better readability