Qt wiki will be updated on October 12th 2023 starting at 11:30 AM (EEST) and the maintenance will last around 2-3 hours. During the maintenance the site will be unavailable.

Coding-Conventions: Difference between revisions

From Qt Wiki
Jump to navigation Jump to search
No edit summary
No edit summary
Line 1: Line 1:
[[Category:Developing_Qt::Guidelines]]
[[Category:Developing_Qt::Guidelines]]


[toc align_right="yes" depth="3"]
[toc align_right="yes" depth="3"]


= Qt Coding Conventions =
= Qt Coding Conventions =


This is an overview of the high-level coding conventions we use when writing Qt code.<br />See [[Qt_Coding_Style]] for the lower-level conventions.
This is an overview of the high-level coding conventions we use when writing Qt code.
See [[Qt_Coding_Style]] for the lower-level conventions.


== C++ features ==
== C++ features ==


* Don't use exceptions
* Don't use exceptions
* Don't use rtti (Run-Time Type Information; that is, the &lt;code&amp;gt;typeinfo&amp;lt;/code&amp;gt; struct, the &lt;code&amp;gt;dynamic_cast&amp;lt;/code&amp;gt; or the &lt;code&amp;gt;typeid&amp;lt;/code&amp;gt; operators, including throwing exceptions)
* Don't use rtti (Run-Time Type Information; that is, the <code>typeinfo</code> struct, the <code>dynamic_cast</code> or the <code>typeid</code> operators, including throwing exceptions)
* Use templates wisely, not just because you can.
* Use templates wisely, not just because you can.


Hint: Use the &lt;code&amp;gt;compile&amp;lt;/code&amp;gt; autotest to see whether a C++ feature is supported by all compilers in the test farm.
Hint: Use the <code>compile</code> autotest to see whether a C++ feature is supported by all compilers in the test farm.


== Conventions in Qt source code ==
== Conventions in Qt source code ==


* All code is ascii only (7-bit characters only, run &lt;code&amp;gt;man ascii&amp;lt;/code&amp;gt; if unsure)
* All code is ascii only (7-bit characters only, run <code>man ascii</code> if unsure)
** Rationale: We have too many locales inhouse and an unhealthy mix of UTF-8 and latin1 systems. Usually, characters &gt; 127 can be broken without you even knowing by clicking SAVE in your favourite editor.
** 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 clicking SAVE in your favourite editor.
** For strings: Use &lt;code&amp;gt;&lt;/code&amp;gt; (where &lt;code&amp;gt;nnn&amp;lt;/code&amp;gt; is the octal representation of whatever character encoding you want your string in) or &lt;code&amp;gt;&lt;/code&amp;gt; (where &lt;code&amp;gt;nn&amp;lt;/code&amp;gt; is hexadecimal). Example: &lt;code&amp;gt;QString s = QString::fromUtf8(&quot;13\005&amp;quot;);&lt;/code&amp;gt;
** For strings: Use <code></code> (where <code>nnn</code> is the octal representation of whatever character encoding you want your string in) or <code></code> (where <code>nn</code> is hexadecimal). Example: <code>QString s = QString::fromUtf8("13\005");</code>
** For umlauts in documentation, or other non-ASCII characters, either use qdoc's command or use the relevant macro; e.g. for &amp;uuml;
** For umlauts in documentation, or other non-ASCII characters, either use qdoc's command or use the relevant macro; e.g. for &amp;uuml;
* Every QObject subclass must have a &lt;code&amp;gt;Q_OBJECT&amp;lt;/code&amp;gt; macro, even if it doesn't have signals or slots, otherwise &lt;code&amp;gt;qobject_cast&amp;lt;/code&amp;gt; will fail.
* Every QObject subclass must have a <code>Q_OBJECT</code> macro, even if it doesn't have signals or slots, otherwise <code>qobject_cast</code> will fail.
* Normalize the arguments for signals + slots (see &lt;code&amp;gt;QMetaObject::normalizedSignature&amp;lt;/code&amp;gt;) inside connect statements to get faster signal/slot lookups. You can use &lt;code&amp;gt;$QTDIR/util/normalize&amp;lt;/code&amp;gt; to normalize existing code.
* Normalize the arguments for signals + slots (see <code>QMetaObject::normalizedSignature</code>) inside connect statements to get faster signal/slot lookups. You can use <code>$QTDIR/util/normalize</code> to normalize existing code.


=== Including headers ===
=== Including headers ===


* In public header files, always use this form to include Qt headers: &lt;code&amp;gt;#include &lt;QtCore/qwhatever.h&amp;gt;&lt;/code&amp;gt;. The library prefix is neccessary for Mac OS X frameworks and is very convenient for non-qmake projects.
* In public header files, always use this form to include Qt headers: <code>#include <QtCore/qwhatever.h></code>. 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. Separate the categories with empty lines.
* In source files, include specialized headers first, then generic headers. Separate the categories with empty lines.


<code><br /> #include &lt;qstring.h&amp;gt; // Qt class
<code>
#include <qstring.h> // Qt class


#include &lt;new&amp;gt; // STL stuff
#include <new> // STL stuff


#include &lt;limits.h&amp;gt; // system stuff<br /></code>
#include <limits.h> // system stuff
</code>


* If you need to include &lt;code&amp;gt;qplatformdefs.h&amp;lt;/code&amp;gt;, always include it as the '''first''' header file.
* If you need to include <code>qplatformdefs.h</code>, always include it as the '''first''' header file.
* If you need to include private headers, be careful. Then use the following syntax. It doesn't matter in which module or directory whatever_p.h is in.
* If you need to include private headers, be careful. Then use the following syntax. It doesn't matter in which module or directory whatever_p.h is in.


<code><br /> #include &lt;private/whatever_p.h&amp;gt;<br /></code>
<code>
#include <private/whatever_p.h>
</code>


* If you need to include &lt;code&amp;gt;qt_x11_p.h&amp;lt;/code&amp;gt;, always include it as the '''last''' header file.
* If you need to include <code>qt_x11_p.h</code>, always include it as the '''last''' header file.


=== Casting ===
=== Casting ===


* Avoid C casts, prefer C++ casts (&lt;code&amp;gt;static_cast&amp;lt;/code&amp;gt;, &lt;code&amp;gt;const_cast&amp;lt;/code&amp;gt;, &lt;code&amp;gt;reinterpret_cast&amp;lt;/code&amp;gt;)
* Avoid C casts, prefer C++ casts (<code>static_cast</code>, <code>const_cast</code>, <code>reinterpret_cast</code>)
** Rationale: Both reinterpret_cast and C-style casts are dangerous, but at least reinterpret_cast won't remove the const modifier
** Rationale: Both reinterpret_cast and C-style casts are dangerous, but at least reinterpret_cast won't remove the const modifier
* Don't use &lt;code&amp;gt;dynamic_cast&amp;lt;/code&amp;gt;, use &lt;code&amp;gt;qobject_cast&amp;lt;/code&amp;gt; for QObjects or refactor your design, for example by introducing a type() method (see QListWidgetItem)
* Don't use <code>dynamic_cast</code>, use <code>qobject_cast</code> for QObjects or refactor your design, for example by introducing a type() method (see QListWidgetItem)
* Use the constructor to cast simple types: &lt;code&amp;gt;int(myFloat)&lt;/code&amp;gt; instead of &lt;code&amp;gt;(int)myFloat&amp;lt;/code&amp;gt;
* Use the constructor to cast simple types: <code>int(myFloat)</code> instead of <code>(int)myFloat</code>
** Rationale: When refactoring code, the compiler will instantly let you know if the cast would become dangerous.
** Rationale: When refactoring code, the compiler will instantly let you know if the cast would become dangerous.


Line 54: Line 59:
* 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).
* 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).


<code><br /> QString s;<br /> return condition ? s : &quot;nothing&amp;quot;; // crash at runtime - QString vs. const char *<br /></code>
<code>
QString s;
return condition ? s : "nothing"; // crash at runtime - QString vs. const char *
</code>


* Be extremely careful about alignment.
* 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 &lt;code&amp;gt;const char '''&lt;/code&amp;gt; is cast to an &lt;code&amp;gt;const int'''&lt;/code&amp;gt;, it'll crash on machines where integers have to be aligned at a two- or four-byte 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 <code>const char '''</code> is cast to an <code>const int'''</code>, 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 &lt;code&amp;gt;AlignHelper&amp;lt;/code&amp;gt; are aligned at integer-boundaries.
** Use a union to force the compiler to align variables correctly. In the example below, you can be sure that all instances of <code>AlignHelper</code> are aligned at integer-boundaries.


<code><br /> union AlignHelper {<br /> char c;<br /> int i;<br /> };<br /></code>
<code>
union AlignHelper {
char c;
int i;
};
</code>


* 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:
* 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:


<code><br /> // global scope<br /> static const QString x; // Wrong - default constructor needs to be run to initialize x<br /> static const QString y = &quot;Hello&amp;quot;; // Wrong - constructor that takes a const char * has to be run<br /> QString z; // super wrong<br /> static const int i = foo(); // wrong - call time of foo() undefined, might not be called at all<br /></code>
<code>
// global scope
static const QString x; // Wrong - default constructor needs to be run to initialize x
static const QString y = "Hello"; // Wrong - constructor that takes a const char * has to be run
QString z; // super wrong
static const int i = foo(); // wrong - call time of foo() undefined, might not be called at all
</code>


Things you can do:
Things you can do:


<code><br /> // global scope<br /> static const char x[] = &quot;someText&amp;quot;; // Works - no constructor must be run, x set at compile time<br /> static int y = 7; // Works - y will be set at compile time<br /> static MyStruct s = {1, 2, 3}; // Works - will be initialized statically, no code being run<br /> static QString '''ptr = 0; // Pointers to objects are ok - no code needed to be run to initialize ptr<br /></code>
<code>
<br />Use &lt;code&amp;gt;Q_GLOBAL_STATIC&amp;lt;/code&amp;gt; to create static global objects instead:
// global scope
<br /><code><br /> Q_GLOBAL_STATIC(QString, s)
static const char x[] = "someText"; // Works - no constructor must be run, x set at compile time
<br /> void foo()<br /> {<br /> s()<s>&gt;append(&quot;moo&amp;quot;);<br /> }<br /></code>
static int y = 7; // Works - y will be set at compile time
<br />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.
static MyStruct s = {1, 2, 3}; // Works - will be initialized statically, no code being run
<br />* A &lt;code&amp;gt;char&amp;lt;/code&amp;gt; is signed or unsigned dependent on the architecture. Use &lt;code&amp;gt;signed char&amp;lt;/code&amp;gt; or &lt;code&amp;gt;uchar&amp;lt;/code&amp;gt; if you explicitely want a signed/unsigned char. The following code will break on ppc, for example:
static QString '''ptr = 0; // Pointers to objects are ok - no code needed to be run to initialize ptr
<br /><code><br /> char c = 'A';<br /> if (c &lt; 0) { … } // WRONG</s> condition is always true on platforms where the default is unsigned char<br /></code>
</code>
<br />''' Avoid 64-bit enum values.<br />'''''' The aapcs embedded ABI hard codes all enum values to a 32-bit integer.<br />'''''' Microsoft compilers don't support 64-bit enum values. (confirmed with Microsoft ® C/C++ Optimizing Compiler Version 15.00.30729.01 for x64)
 
Use <code>Q_GLOBAL_STATIC</code> to create static global objects instead:
 
<code>
Q_GLOBAL_STATIC(QString, s)
 
void foo()
{
s()->append("moo");
}
</code>
 
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 <code>char</code> is signed or unsigned dependent on the architecture. Use <code>signed char</code> or <code>uchar</code> if you explicitely want a signed/unsigned char. The following code will break on ppc, for example:
 
<code>
char c = 'A';
if (c < 0) { … } // WRONG- condition is always true on platforms where the default is unsigned char
</code>
 
''' 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 ===
=== Aesthetics ===


* Prefer enums to define constants over &lt;code&amp;gt;static const int&amp;lt;/code&amp;gt; or defines.
* Prefer enums to define constants over <code>static const int</code> or defines.
** enum values will be replaced by the compiler at compile time, resulting in faster code
** enum values will be replaced by the compiler at compile time, resulting in faster code
** defines are not namespace safe (and look ugly)
** defines are not namespace safe (and look ugly)
Line 85: Line 127:
** Most IDEs will show the argument names in their completion-box.
** Most IDEs will show the argument names in their completion-box.
** It will look better in the documentation
** It will look better in the documentation
** Bad style: &lt;code&amp;gt;doSomething(QRegion rgn, QPoint p)&lt;/code&amp;gt; - use &lt;code&amp;gt;doSomething(QRegion clientRegion, QPoint gravitySource)&lt;/code&amp;gt; instead
** Bad style: <code>doSomething(QRegion rgn, QPoint p)</code> - use <code>doSomething(QRegion clientRegion, QPoint gravitySource)</code> instead
* When reimplementing a virtual method, do not put the `virtual` keyword in the header file.<br />On Qt5, annotate them with the &quot;Q_DECL_OVERRIDE&amp;quot;:http://doc.qt.io/qt-5.0/qtcore/qtglobal.html#Q_DECL_OVERRIDE macro after the function declaration, just before the ';' (or the '{' ).
* When reimplementing a virtual method, do not put the `virtual` keyword in the header file.
On Qt5, annotate them with the "Q_DECL_OVERRIDE":http://doc.qt.io/qt-5.0/qtcore/qtglobal.html#Q_DECL_OVERRIDE macro after the function declaration, just before the ';' (or the '{' ).


=== Things to avoid ===
=== Things to avoid ===
Line 93: Line 136:
** The destructors are not virtual, leading to potential memory leaks
** The destructors are not virtual, leading to potential memory leaks
** The symbols are not exported (and mostly inline), leading to interesting symbol clashes.
** The symbols are not exported (and mostly inline), leading to interesting symbol clashes.
** Example: Library A has &lt;code&amp;gt;class Q_EXPORT X: public QList&amp;lt;QVariant&amp;gt; {};&lt;/code&amp;gt; and library B has &lt;code&amp;gt;class Q_EXPORT Y: public QList&amp;lt;QVariant&amp;gt; {};&lt;/code&amp;gt;. Suddenly, QList&amp;lt;QVariant&amp;gt;'s symbols are exported from two libraries - /clash/.
** Example: Library A has <code>class Q_EXPORT X: public QList<QVariant> {};</code> and library B has <code>class Q_EXPORT Y: public QList<QVariant> {};</code>. 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.
* Don't mix const and non-const iterators. This will silently crash on broken compilers.


<code><br /> for (Container::const_iterator it = c.begin(); it != c.end(); +''it) // W R O N G<br /> for (Container::const_iterator it = c.constBegin(); it != c.constEnd();it) // Right<br /></code>
<code>
<br />* 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 &lt;nop&amp;gt;ActiveQt or browser plugin. Code like this will easily break:
for (Container::const_iterator it = c.begin(); it != c.end(); +''it) // W R O N G
<br /><code><br /> static QObject '''obj = 0;<br /> if (!obj)<br /> obj = new QObject(QCoreApplication::instance());<br /></code>
for (Container::const_iterator it = c.constBegin(); it != c.constEnd();it) // Right
<br />If the &lt;code&amp;gt;QCoreApplication&amp;lt;/code&amp;gt; application is destroyed, &lt;code&amp;gt;obj&amp;lt;/code&amp;gt; will be a dangling pointer. Use &lt;code&amp;gt;Q_GLOBAL_STATIC&amp;lt;/code&amp;gt; for static global objects or &lt;code&amp;gt;qAddPostRoutine&amp;lt;/code&amp;gt; to clean up.
</code>
<br />''' Avoid the use of anonymous namespaces in favor of the static keyword if possible. A name localized to the compilation unit with &lt;code&amp;gt;static&amp;lt;/code&amp;gt; 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)
 
* 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:
 
<code>
static QObject '''obj = 0;
if (!obj)
obj = new QObject(QCoreApplication::instance());
</code>
 
If the <code>QCoreApplication</code> application is destroyed, <code>obj</code> will be a dangling pointer. Use <code>Q_GLOBAL_STATIC</code> for static global objects or <code>qAddPostRoutine</code> 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 <code>static</code> 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 ===
=== Binary and Source Compatibility ===
Line 122: Line 176:
* 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.
* 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 &quot;symbols&amp;quot; autotest to find violations.
* All exported functions from Qt must start with either 'q' or 'Q'. Use the "symbols" autotest to find violations.


=== Namespacing ===
=== Namespacing ===


* Read [[Qt In Namespace|Qt in Namespace]] and keep in mind that all of Qt except Tests and Webkit is &quot;namespaced&amp;quot; code.
* Read [[Qt In Namespace|Qt in Namespace]] and keep in mind that all of Qt except Tests and Webkit is "namespaced" code.


=== Operators ===
=== Operators ===


* &quot;The decision between member and non-member&amp;quot;:http://stackoverflow.com/questions/4421706/operator-overloading/4421729#4421729
* "The decision between member and non-member":http://stackoverflow.com/questions/4421706/operator-overloading/4421729#4421729


A binary operator that treats both of its arguments equally should not be a member. Because, in addition to the reasons mentioned in the stack overflow answer, the arguments are not equal when the operator is a member.
A binary operator that treats both of its arguments equally should not be a member. Because, in addition to the reasons mentioned in the stack overflow answer, the arguments are not equal when the operator is a member.
Line 136: Line 190:
Example with QLineF which unfortunately has its operator== as a member:
Example with QLineF which unfortunately has its operator== as a member:


<code>QLineF lineF;<br />QLine lineN;
<code>QLineF lineF;
QLine lineN;


if (lineF  lineN) // Ok,  lineN is implicitly converted to QLineF
if (lineF  lineN) // Ok,  lineN is implicitly converted to QLineF
Line 147: Line 202:
Our public header files have to survive the strict settings of some of our users. All installed headers have to follow these rules:
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 (&lt;code&amp;gt;-Wold-style-cast&amp;lt;/code&amp;gt;)
* No C style casts (<code>-Wold-style-cast</code>)
** Use static_cast, const_cast or reinterpret_cast
** Use static_cast, const_cast or reinterpret_cast
** for basic types, use the constructor form: int(a) instead of (int)a
** for basic types, use the constructor form: int(a) instead of (int)a
** See chapter &quot;Casting&amp;quot; for more info
** See chapter "Casting" for more info


* No float comparisons (&lt;code&amp;gt;-Wfloat-equal&amp;lt;/code&amp;gt;)
* No float comparisons (<code>-Wfloat-equal</code>)
** Use qFuzzyCompare to compare values with a delta
** 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.  
** Use qIsNull to check whether a float is binary 0, instead of comparing it to 0.0.  


* Don't hide virtual methods in subclasses (&lt;code&amp;gt;-Woverloaded-virtual&amp;lt;/code&amp;gt;)
* Don't hide virtual methods in subclasses (<code>-Woverloaded-virtual</code>)
** If the baseclass &lt;code&amp;gt;A&amp;lt;/code&amp;gt; has a &lt;code&amp;gt;virtual int val()&lt;/code&amp;gt; and subclass &lt;code&amp;gt;B&amp;lt;/code&amp;gt; an overload with the same name, &lt;code&amp;gt;int val(int x)&lt;/code&amp;gt;, &lt;code&amp;gt;A&amp;lt;/code&amp;gt;'s &lt;code&amp;gt;val&amp;lt;/code&amp;gt; function is hidden. Use the &lt;code&amp;gt;using&amp;lt;/code&amp;gt; keyword to make it visible again, and add the following silly workaround for broken compilers:
** If the baseclass <code>A</code> has a <code>virtual int val()</code> and subclass <code>B</code> an overload with the same name, <code>int val(int x)</code>, <code>A</code>'s <code>val</code> function is hidden. Use the <code>using</code> keyword to make it visible again, and add the following silly workaround for broken compilers:


<code><br /> class B: public A<br /> {<br /> #ifdef Q_NO_USING_KEYWORD<br /> inline int val() { return A::val(); }<br /> #else<br /> using A::val;<br /> #endif<br /> };<br /> </code>
<code>
class B: public A
{
#ifdef Q_NO_USING_KEYWORD
inline int val() { return A::val(); }
#else
using A::val;
#endif
};
</code>


* Don't shadow variables (&lt;code&amp;gt;<s>Wshadow&amp;lt;/code&amp;gt;)<br />'''''' avoid things like &lt;code&amp;gt;this</s>&gt;x = x;&lt;/code&amp;gt;
* Don't shadow variables (<code>-Wshadow</code>)
'''''' avoid things like <code>this->x = x;</code>
** don't give variables the same name as functions declared in your class
** don't give variables the same name as functions declared in your class


* Always check whether a preprocessor variable is defined before probing its value (&lt;code&amp;gt;<s>Wundef&amp;lt;/code&amp;gt;)
* Always check whether a preprocessor variable is defined before probing its value (<code>-Wundef</code>)
<br /><code><br /> #if Foo  0  // W R O N G
 
         #if defined(Foo) &amp;amp;&amp;amp; Foo  0 // Right<br /> #if Foo</s> 0 == 0 // Clever, are we? Use the one above instead, for better readability
<code>
#if Foo  0  // W R O N G
         #if defined(Foo) &amp;amp;&amp;amp; Foo  0 // Right
#if Foo- 0 == 0 // Clever, are we? Use the one above instead, for better readability

Revision as of 08:44, 25 February 2015


[toc align_right="yes" depth="3"]

Qt Coding Conventions

This is an overview of the high-level coding conventions we use when writing Qt code. See Qt_Coding_Style for the lower-level conventions.

C++ features

  • Don't use exceptions
  • Don't use rtti (Run-Time Type Information; that is, the
    typeinfo
    
    struct, the
    dynamic_cast
    
    or the
    typeid
    
    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 clicking SAVE in your favourite editor.
    • For strings: Use
      (where
      nnn
      
      is the octal representation of whatever character encoding you want your string in) or
      (where
      nn
      
      is hexadecimal). Example:
      QString s = QString::fromUtf8("13\005");
      
    • For umlauts in documentation, or other non-ASCII characters, either use qdoc's command or use the relevant macro; e.g. for &uuml;
  • Every QObject subclass must have a
    Q_OBJECT
    
    macro, even if it doesn't have signals or slots, otherwise
    qobject_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. Separate the categories with empty lines.
 #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 the first header file.
  • If you need to include private headers, be careful. Then use the following syntax. It doesn't matter in which module or directory whatever_p.h is in.
 #include <private/whatever_p.h>
  • 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
    
    , use
    qobject_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 an
      const 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.
 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 QString x; // Wrong - default constructor needs to be run to initialize x
 static const QString y = "Hello"; // Wrong - constructor that takes a const char * has to be run
 QString z; // super wrong
 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:

 Q_GLOBAL_STATIC(QString, s)

 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. Use
    signed char
    
    or
    uchar
    
    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)
      
      - use
      doSomething(QRegion clientRegion, QPoint gravitySource)
      
      instead
  • When reimplementing a virtual method, do not put the `virtual` keyword in the header file.

On Qt5, annotate them with the "Q_DECL_OVERRIDE":http://doc.qt.io/qt-5.0/qtcore/qtglobal.html#Q_DECL_OVERRIDE macro after the function declaration, just before the ';' (or the '{' ).

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 has
      class 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:
 static QObject '''obj = 0;
 if (!obj)
 obj = new QObject(QCoreApplication::instance());

If the

QCoreApplication

application is destroyed,

obj

will be a dangling pointer. Use

Q_GLOBAL_STATIC

for static global objects or

qAddPostRoutine

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]|Binary Compatibility Workarounds]] for ways to keep b/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.

Operators

A binary operator that treats both of its arguments equally should not be a member. Because, in addition to the reasons mentioned in the stack overflow answer, the arguments are not equal when the operator is a member.

Example with QLineF which unfortunately has its operator== as a member:

QLineF lineF;
QLine lineN;

if (lineF  lineN) // Ok,  lineN is implicitly converted to QLineF
if (lineN  lineF) // Error: QLineF cannot be converted implicitly to QLine, and the LHS is a member so no conversion applies

If the operator== was outside of the class, conversion rules would apply equally for both sides.

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 a
      virtual int val()
      
      and subclass
      B
      
      an overload with the same name,
      int val(int x)
      
      ,
      A
      
      's
      val
      
      function is hidden. Use the
      using
      
      keyword to make it visible again, and add the following silly workaround for broken compilers:
 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
  • Always check whether a preprocessor variable is defined before probing its value (
    -Wundef
    
    )

#if Foo   0  // W R O N G
       #if defined(Foo) &amp;&amp; Foo  0 // Right
#if Foo- 0 == 0 // Clever, are we? Use the one above instead, for better readability