Coding Conventions: Difference between revisions
(Added link to QML conventions.) |
(Updated statement about not using unnamed namespaces according to discussion on mailing list. See [Development] Can we remove recommendation against unnamed namespaces from Qt coding conventions?) |
||
(15 intermediate revisions by 9 users not shown) | |||
Line 2: | Line 2: | ||
This is an overview of the high-level coding conventions we use when writing Qt code. | 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. | See [[Qt Coding Style]] for the lower-level conventions, [[API Design Principles]] for higher-level guidance. | ||
For QML, see [http://doc.qt.io/qt-5/qml-codingconventions.html QML Coding Conventions]. | For QML, see [http://doc.qt.io/qt-5/qml-codingconventions.html QML Coding Conventions], | ||
for examples see [[Qt6/Example-Guideline]]. | |||
== C++ features == | ==C++ features== | ||
* Don't use exceptions | *Don't use exceptions | ||
* Don't use rtti (Run-Time Type Information; that is, the <tt>typeinfo</tt> struct, the <tt>dynamic_cast</tt> or the <tt>typeid</tt> operators, including throwing exceptions) | *Don't use rtti (Run-Time Type Information; that is, the <tt>typeinfo</tt> struct, the <tt>dynamic_cast</tt> or the <tt>typeid</tt> operators, including throwing exceptions) | ||
* Use templates wisely, not just because you can. | *Use templates wisely, not just because you can. | ||
Hint: Use the <tt>compile</tt> autotest to see whether a C++ feature is supported by all compilers in the test farm. | Hint: Use the <tt>compile</tt> 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 | *All source code is UTF-8 | ||
*Every QObject subclass must have a <tt>Q_OBJECT</tt> macro, even if it doesn't have signals or slots, otherwise <tt>qobject_cast</tt> will fail. | |||
*Normalize the arguments for signals + slots (see <tt>QMetaObject::normalizedSignature</tt>) inside connect statements to get faster signal/slot lookups. You can use <tt>qtrepotools/util/normalize</tt> to normalize existing code. | |||
* Every QObject subclass must have a <tt>Q_OBJECT</tt> macro, even if it doesn't have signals or slots, otherwise <tt>qobject_cast</tt> will fail. | |||
* Normalize the arguments for signals + slots (see <tt>QMetaObject::normalizedSignature</tt>) inside connect statements to get faster signal/slot lookups. You can use <tt> | |||
=== Including headers === | ===Include guards=== | ||
* always use conventional include guards in public and private library headers: | |||
<syntaxhighlight lang="cpp"> | |||
// in qclassname.h | |||
#ifndef QCLASSNAME_H | |||
#define QCLASSNAME_H | |||
// public declarations | |||
#endif // QCLASSNAME_H | |||
</syntaxhighlight> | |||
<syntaxhighlight lang="cpp"> | |||
// in qclassname_p.h | |||
#ifndef QCLASSNAME_P_H | |||
#define QCLASSNAME_P_H | |||
// private declarations | |||
#endif // QCLASSNAME_P_H | |||
</syntaxhighlight> | |||
* in headers that are part of tools, examples and demos, or tests, and never included by Qt user code, you may use <tt>#pragma once</tt> instead | |||
Rationale: <tt>#pragma once</tt> is not well enough defined, and not part of the standard. We cannot make any assumptions about how Qt is installed, used as part of a larger SDK etc. To avoid issues in user installations, we use the conservative approach. To avoid clashes, make sure that new class and file names are unique within all of Qt's submodules. | |||
===Including headers=== | |||
<ul> | <ul> | ||
<li>In public header files, always use this form to include Qt headers: <tt>#include <QtCore/qwhatever.h></tt>. The library prefix is | <li>In public header files, always use this form to include Qt headers: <tt>#include <QtCore/qwhatever.h></tt>. The library prefix is necessary for Mac OS X frameworks and is very convenient for non-qmake projects.</li> | ||
</li> | |||
<li>In source files, include specialized headers first, then generic headers. Separate the categories with empty lines. | <li>In source files, include specialized headers first, then generic headers. Separate the categories with empty lines.</li> | ||
< | <syntaxhighlight lang="cpp"> | ||
#include <qstring.h> | |||
// #include Qt stuff | |||
// ... | |||
#include <new> | |||
// #include STL stuff | |||
// ... | |||
#include <limits.h> | |||
// #include system stuff | |||
</ | // ...</syntaxhighlight> | ||
<li>If you need to include <tt>qplatformdefs.h</tt>, always include it as the '''first''' header file. | <li>If you need to include <tt>qplatformdefs.h</tt>, always include it as the '''first''' header file.</li> | ||
</li> | |||
<li>If you need to include private headers, be careful. Use the following syntax, irrespective of which module or directory whatever_p.h is in. | <li>If you need to include private headers, be careful. Use the following syntax, irrespective of which module or directory whatever_p.h is in.</li> | ||
< | <syntaxhighlight lang="cpp"> | ||
#include <private/whatever_p.h> | |||
</ | </syntaxhighlight> | ||
</ul> | </ul> | ||
=== Casting === | ===Casting=== | ||
* Avoid C casts, prefer C++ casts (<tt>static_cast</tt>, <tt>const_cast</tt>, <tt>reinterpret_cast</tt>) | *Avoid C casts, prefer C++ casts (<tt>static_cast</tt>, <tt>const_cast</tt>, <tt>reinterpret_cast</tt>) | ||
** 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 <tt>dynamic_cast</tt>, use <tt>qobject_cast</tt> for QObjects or refactor your design, for example by introducing a type() method (see QListWidgetItem) | *Don't use <tt>dynamic_cast</tt>, use <tt>qobject_cast</tt> for QObjects or refactor your design, for example by introducing a type() method (see QListWidgetItem) | ||
* Use the constructor to cast simple types: <tt>int(myFloat)</tt> instead of <tt>(int)myFloat</tt> | *Use the constructor to cast simple types: <tt>int(myFloat)</tt> instead of <tt>(int)myFloat</tt> | ||
** 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. | ||
=== Compiler/Platform specific issues === | ===Compiler/Platform specific issues=== | ||
<ul> | <ul> | ||
<li>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). | <li>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).</li> | ||
< | <syntaxhighlight lang="cpp"> | ||
QString s; | |||
return condition ? s : "nothing"; // crash at runtime - QString vs. const char *</syntaxhighlight> | |||
</ | |||
<li>Be extremely careful about alignment. | <li>Be extremely careful about alignment. | ||
Line 78: | Line 104: | ||
</li> | </li> | ||
<li>Use a union to force the compiler to align variables correctly. In the example below, you can be sure that all instances of <tt>AlignHelper</tt> are aligned at integer-boundaries. | <li>Use a union to force the compiler to align variables correctly. In the example below, you can be sure that all instances of <tt>AlignHelper</tt> are aligned at integer-boundaries.</li> | ||
</li> | |||
</ul> | </ul> | ||
</li> | </li> | ||
< | <syntaxhighlight lang="cpp"> | ||
union AlignHelper { | |||
char c; | |||
int i; | |||
}; | |||
</syntaxhighlight> | |||
<code> | <li>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:</li> | ||
<syntaxhighlight lang="cpp"> | |||
// 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 | |||
</syntaxhighlight> | |||
Things you can do: | Things you can do: | ||
< | <syntaxhighlight lang="cpp"> | ||
// 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 | |||
</ | </syntaxhighlight> | ||
Use <tt>Q_GLOBAL_STATIC</tt> to create static global objects instead: | Use <tt>Q_GLOBAL_STATIC</tt> to create static global objects instead: | ||
< | <syntaxhighlight lang="cpp"> | ||
Q_GLOBAL_STATIC(QString, s) | |||
void foo() | |||
{ | |||
s()->append("moo"); | |||
} | |||
</ | </syntaxhighlight> | ||
Note: Static objects in a scope are no problem, the constructor will be run the first time the scope is entered. | Note: Static objects in a scope are no problem, the constructor will be run the first time the scope is entered. Such code is reentrant since C++11. | ||
<li>A <tt>char</tt> is signed or unsigned dependent on the architecture. Use <tt>signed char</tt> or <tt>unsigned char</tt> if you explicitely want a signed/unsigned char. The condition in the following code is always true on platforms where the default char is unsigned. | <li>A <tt>char</tt> is signed or unsigned dependent on the architecture. Use <tt>signed char</tt> or <tt>unsigned char</tt> if you explicitely want a signed/unsigned char. The condition in the following code is always true on platforms where the default char is unsigned. | ||
< | <syntaxhighlight lang="cpp"> | ||
char c; // c can't be negative if it is unsigned | |||
/********/ | /********/ | ||
/*******/ | /*******/ | ||
if (c > 0) { … } // WRONG - condition is always true on platforms where the default is unsigned | |||
</ | </syntaxhighlight> | ||
</li> | </li> | ||
<li>Avoid 64-bit enum values. | <li>Avoid 64-bit enum values. | ||
* The aapcs embedded ABI hard codes all enum values to a 32-bit integer. | *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) | *Microsoft compilers don't support 64-bit enum values. (confirmed with Microsoft ® C/C++ Optimizing Compiler Version 15.00.30729.01 for x64) | ||
</li> | </li> | ||
</ul> | </ul> | ||
=== Aesthetics === | ===Aesthetics=== | ||
* Prefer enums to define constants over <tt>static const int</tt> or defines. | *Prefer enums to define constants over <tt>static const int</tt> 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) | ||
* Prefer verbose argument names in headers. | *Prefer verbose argument names in headers. | ||
** 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: <tt>doSomething(QRegion rgn, QPoint p)</tt> - use <tt>doSomething(QRegion clientRegion, QPoint gravitySource)</tt> instead | **Bad style: <tt>doSomething(QRegion rgn, QPoint p)</tt> - use <tt>doSomething(QRegion clientRegion, QPoint gravitySource)</tt> instead | ||
* When reimplementing a virtual method, do not put the `virtual` keyword in the header file. <br />On Qt5, annotate them with the | *When reimplementing a virtual method, do not put the `virtual` keyword in the header file. <br />On Qt5, annotate them with the <kbd>override</kbd> keyword after the function declaration, just before the ';' (or the '{' ). | ||
=== Things to avoid === | ===Things to avoid=== | ||
<ul> | <ul> | ||
Line 166: | Line 190: | ||
</ul> | </ul> | ||
</li> | </li> | ||
<li>Don't mix const and non-const iterators. This will silently crash on broken compilers. | <li>Don't mix const and non-const iterators. This will silently crash on broken compilers.</li> | ||
< | <syntaxhighlight lang="cpp"> | ||
for (Container::const_iterator it = c.begin(); it != c.end(); ++it) // W R O N G | |||
for (Container::const_iterator it = c.cbegin(); it != c.cend(); ++it) // Right | |||
</ | </syntaxhighlight> | ||
<li> | <li>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 ActiveQt or browser plugin. Code like this will easily break: | ||
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 ActiveQt or browser plugin. Code like this will easily break: | |||
< | <syntaxhighlight lang="cpp"> | ||
static QObject *obj = 0; | |||
if (!obj) | |||
obj = new QObject(QCoreApplication::instance()); | |||
</ | </syntaxhighlight> | ||
If the <tt>QCoreApplication</tt> application is destroyed, <tt>obj</tt> will be a dangling pointer. Use <tt>Q_GLOBAL_STATIC</tt> for static global objects or <tt>qAddPostRoutine</tt> to clean up. | If the <tt>QCoreApplication</tt> application is destroyed, <tt>obj</tt> will be a dangling pointer. Use <tt>Q_GLOBAL_STATIC</tt> for static global objects or <tt>qAddPostRoutine</tt> to clean up. | ||
</li> | </li> | ||
<li> | <li>Use the static keyword with local functions, even inside anonymous namespaces. Rationale: `static` is attached to individual functions, not a scope of uncertain extent. This helps to understand the context when working on unfamiliar code. | ||
</li> | </li> | ||
</ul> | </ul> | ||
=== Binary and Source Compatibility === | ===Binary and Source Compatibility=== | ||
* Definitions: | *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 | **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 | **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 | **Forward binary compatibility: Code linked to a newer version of the library works with an older library | ||
** Source code compatibility: Code compiles without modification | **Source code compatibility: Code compiles without modification | ||
* Keep backward binary compatibility + backward source code compatibility in minor releases | *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 | *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 add/remove any public API (e.g. global functions, public/protected/private methods) | ||
** Don't reimplement methods (not even inlines, nor protected/private methods) | **Don't reimplement methods (not even inlines, nor protected/private methods) | ||
** Check [[Binary Compatibility Workarounds]] for ways to keep b/c | **Check [[Binary Compatibility Workarounds]] for ways to keep b/c | ||
* Info on binary compatibility: https://community.kde.org/Policies/Binary_Compatibility_Issues_With_C++ | *Info on binary compatibility: https://community.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. | *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. | *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]] and keep in mind that all of Qt except Tests and Webkit is "namespaced" code. | Read [[Qt In Namespace]] and keep in mind that all of Qt except Tests and Webkit is "namespaced" code. | ||
=== Operators === | ===Operators=== | ||
[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 "The decision between member and non-member"] | ||
Line 219: | Line 241: | ||
Example with QLineF which unfortunately has its operator== as a member: | Example with QLineF which unfortunately has its operator== as a member: | ||
< | <syntaxhighlight lang="cpp"> | ||
QLineF lineF; | QLineF lineF; | ||
QLine lineN; | QLine lineN; | ||
Line 225: | Line 247: | ||
if (lineF == lineN) // Ok, lineN is implicitly converted to QLineF | 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 (lineN == lineF) // Error: QLineF cannot be converted implicitly to QLine, and the LHS is a member so no conversion applies | ||
</ | </syntaxhighlight> | ||
If the operator== was outside of the class, conversion rules would apply equally for both sides. | If the operator== was outside of the class, conversion rules would apply equally for both sides. | ||
== Conventions for public header files == | ==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: | Our public header files have to survive the strict settings of some of our users. All installed headers have to follow these rules: | ||
Line 235: | Line 257: | ||
<ul> | <ul> | ||
<li>No C style casts (<tt>-Wold-style-cast</tt>) | <li>No C style casts (<tt>-Wold-style-cast</tt>) | ||
* 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 "Casting" for more info | *See chapter "Casting" for more info | ||
</li> | </li> | ||
<li>No float comparisons (<tt>-Wfloat-equal</tt>) | <li>No float comparisons (<tt>-Wfloat-equal</tt>) | ||
* 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. | ||
</li> | </li> | ||
<li>Don't hide virtual methods in subclasses (<tt>-Woverloaded-virtual</tt>) | <li>Don't hide virtual methods in subclasses (<tt>-Woverloaded-virtual</tt>) | ||
Line 247: | Line 269: | ||
<li>If the baseclass <tt>A</tt> has a <tt>virtual int val()</tt> and subclass <tt>B</tt> an overload with the same name, <tt>int val(int x)</tt>, <tt>A</tt>'s <tt>val</tt> function is hidden. Use the <tt>using</tt> keyword to make it visible again: | <li>If the baseclass <tt>A</tt> has a <tt>virtual int val()</tt> and subclass <tt>B</tt> an overload with the same name, <tt>int val(int x)</tt>, <tt>A</tt>'s <tt>val</tt> function is hidden. Use the <tt>using</tt> keyword to make it visible again: | ||
< | <syntaxhighlight lang="cpp"> | ||
class B: public A | |||
{ | |||
using A::val; | |||
int val(int x); | |||
}; | |||
</syntaxhighlight> | |||
</li> | </li> | ||
</ul> | </ul> | ||
Line 258: | Line 281: | ||
<li>Don't shadow variables (<tt>-Wshadow</tt>) | <li>Don't shadow variables (<tt>-Wshadow</tt>) | ||
* avoid things like <tt>this->x = x;</tt> | *avoid things like <tt>this->x = x;</tt> | ||
* 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 | ||
</li> | </li> | ||
<li>Always check whether a preprocessor variable is defined before probing its value (<tt>-Wundef</tt>) | <li>Always check whether a preprocessor variable is defined before probing its value (<tt>-Wundef</tt>) | ||
< | <syntaxhighlight lang="cpp"> | ||
#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 | |||
</ | </syntaxhighlight> | ||
</li> | </li> | ||
</ul> | </ul> | ||
== Conventions for C++11 usage == | ==Conventions for C++11 usage== | ||
'''Note:''' This section is not an accepted convention yet. This section serves as baseline for further discussions. | '''Note:''' This section is not an accepted convention yet. This section serves as baseline for further discussions. | ||
=== Lambdas === | ===Lambdas=== | ||
You can use lambdas with the following restrictions: | You can use lambdas with the following restrictions: | ||
<ul> | <ul> | ||
<li> | <li>If you use static functions from the class that the lambda is located in, refactor the code so you don't use a lambda. For example, instead of | ||
< | <syntaxhighlight lang="cpp"> | ||
void Foo::something() | |||
{ | |||
... | |||
}); | std::generate(begin, end, []() { return Foo::someStaticFunction(); }); | ||
... | |||
} | |||
</syntaxhighlight> | |||
You may be able to simply pass the function pointer: | |||
<syntaxhighlight lang="cpp"> | |||
void Foo::something() | void Foo::something() | ||
{ | { | ||
... | ... | ||
std::generate(begin, end, &Foo::someStaticFunction); | |||
... | ... | ||
} | } | ||
</syntaxhighlight> | |||
The reason for this is that GCC 4.7 and earlier had a bug that required capturing <tt>this</tt> but Clang 5.0 and later will produce a warning if you do: | |||
<syntaxhighlight lang="cpp"> | |||
void Foo::something() | void Foo::something() | ||
{ | { | ||
... | ... | ||
[]() { Foo::someStaticFunction(); } | std::generate(begin, end, [this]() { return Foo::someStaticFunction(); }); | ||
// warning: lambda capture 'this' is not used [-Wunused-lambda-capture] | |||
... | ... | ||
} | } | ||
</ | </syntaxhighlight> | ||
</li> | </li> | ||
Line 328: | Line 348: | ||
<li>Always write parentheses for the parameter list, even if the function does not take parameters. | <li>Always write parentheses for the parameter list, even if the function does not take parameters. | ||
< | <syntaxhighlight lang="cpp"> | ||
[]() { doSomething(); } | []() { doSomething(); } | ||
</syntaxhighlight> | |||
-NOT | -NOT | ||
<syntaxhighlight lang="cpp"> | |||
[] { doSomething(); } | [] { doSomething(); } | ||
</ | </syntaxhighlight> | ||
</li> | </li> | ||
<li>Place the capture-list, parameter list, return type, and opening brace on the first line, the body indented on the following lines, and the closing brace on a new line. | <li>Place the capture-list, parameter list, return type, and opening brace on the first line, the body indented on the following lines, and the closing brace on a new line. | ||
< | <syntaxhighlight lang="cpp"> | ||
[]() -> bool { | []() -> bool { | ||
something(); | something(); | ||
return isSomethingElse(); | return isSomethingElse(); | ||
} | } | ||
</syntaxhighlight> | |||
-NOT- | -NOT- | ||
<syntaxhighlight lang="cpp"> | |||
[]() -> bool { something(); | []() -> bool { something(); | ||
somethingElse(); } | somethingElse(); } | ||
</ | </syntaxhighlight> | ||
</li> | </li> | ||
<li>Place a closing parenthesis and semicolon of an enclosing function call on the same line as the closing brace of the lambda. | <li>Place a closing parenthesis and semicolon of an enclosing function call on the same line as the closing brace of the lambda. | ||
< | <syntaxhighlight lang="cpp"> | ||
foo([]() { | foo([]() { | ||
something(); | something(); | ||
}); | }); | ||
</ | </syntaxhighlight> | ||
</li> | </li> | ||
<li>If you are using a lambda in an 'if' statement, start the lambda on a new line, to avoid confusion between the opening brace for the lambda and the opening brace for the 'if' statement. | <li>If you are using a lambda in an 'if' statement, start the lambda on a new line, to avoid confusion between the opening brace for the lambda and the opening brace for the 'if' statement. | ||
< | <syntaxhighlight lang="cpp"> | ||
if (anyOf(fooList, | if (anyOf(fooList, | ||
[](Foo foo) { | [](Foo foo) { | ||
return foo.isGreat(); | return foo.isGreat(); | ||
}) { | })) { | ||
return; | return; | ||
} | } | ||
</syntaxhighlight> | |||
-NOT- | -NOT- | ||
<syntaxhighlight lang="cpp"> | |||
if (anyOf(fooList, [](Foo foo) { | if (anyOf(fooList, [](Foo foo) { | ||
return foo.isGreat(); | return foo.isGreat(); | ||
}) { | })) { | ||
return; | return; | ||
} | } | ||
</ | </syntaxhighlight> | ||
</li> | </li> | ||
<li>Optionally, place the lambda completely on one line if it fits. | <li>Optionally, place the lambda completely on one line if it fits. | ||
< | <syntaxhighlight lang="cpp"> | ||
foo([]() { return true; }); | foo([]() { return true; }); | ||
Line 389: | Line 409: | ||
... | ... | ||
} | } | ||
</ | </syntaxhighlight> | ||
</li> | </li> | ||
</ul> | </ul> | ||
=== auto Keyword === | ===auto Keyword=== | ||
Optionally, you can use the auto keyword in the following cases. If in doubt, for example if using auto could make the code less readable, do not use auto. Keep in mind that code is read much more often than written. | Optionally, you can use the auto keyword in the following cases. If in doubt, for example if using auto could make the code less readable, do not use auto. Keep in mind that code is read much more often than written. | ||
Line 401: | Line 421: | ||
<li>When it avoids repetition of a type in the same statement. | <li>When it avoids repetition of a type in the same statement. | ||
< | <syntaxhighlight lang="cpp"> | ||
auto something = new MyCustomType; | auto something = new MyCustomType; | ||
auto keyEvent = static_cast<QKeyEvent *>(event); | auto keyEvent = static_cast<QKeyEvent *>(event); | ||
auto myList = QStringList() << QLatin1String("FooThing") << QLatin1String("BarThing"); | auto myList = QStringList() << QLatin1String("FooThing") << QLatin1String("BarThing"); | ||
</ | </syntaxhighlight> | ||
</li> | </li> | ||
<li>When assigning iterator types. | <li>When assigning iterator types. | ||
< | <syntaxhighlight lang="cpp"> | ||
auto it = myList.const_iterator(); | auto it = myList.const_iterator(); | ||
</ | </syntaxhighlight> | ||
</li> | </li> | ||
</ul> | </ul> |
Latest revision as of 08:07, 22 August 2024
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, API Design Principles for higher-level guidance.
For QML, see QML Coding Conventions,
for examples see Qt6/Example-Guideline.
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 source code is UTF-8
- 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 qtrepotools/util/normalize to normalize existing code.
Include guards
- always use conventional include guards in public and private library headers:
// in qclassname.h
#ifndef QCLASSNAME_H
#define QCLASSNAME_H
// public declarations
#endif // QCLASSNAME_H
// in qclassname_p.h
#ifndef QCLASSNAME_P_H
#define QCLASSNAME_P_H
// private declarations
#endif // QCLASSNAME_P_H
- in headers that are part of tools, examples and demos, or tests, and never included by Qt user code, you may use #pragma once instead
Rationale: #pragma once is not well enough defined, and not part of the standard. We cannot make any assumptions about how Qt is installed, used as part of a larger SDK etc. To avoid issues in user installations, we use the conservative approach. To avoid clashes, make sure that new class and file names are unique within all of Qt's submodules.
Including headers
- In public header files, always use this form to include Qt headers: #include <QtCore/qwhatever.h>. The library prefix is necessary 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.
- If you need to include qplatformdefs.h, always include it as the first header file.
- If you need to include private headers, be careful. Use the following syntax, irrespective of which module or directory whatever_p.h is in.
#include <qstring.h>
// #include Qt stuff
// ...
#include <new>
// #include STL stuff
// ...
#include <limits.h>
// #include system stuff
// ...
#include <private/whatever_p.h>
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).
- 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 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.
- 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:
- A char is signed or unsigned dependent on the architecture. Use signed char or unsigned char if you explicitely want a signed/unsigned char. The condition in the following code is always true on platforms where the default char is unsigned.
char c; // c can't be negative if it is unsigned /********/ /*******/ if (c > 0) { … } // WRONG - condition is always true on platforms where the default is unsigned
- 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)
QString s;
return condition ? s : "nothing"; // crash at runtime - QString vs. const char *
union AlignHelper {
char c;
int i;
};
// 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. Such code is reentrant since C++11.
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 override keyword 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 and library B has
class Q_EXPORT X: public QList<QVariant> {};
Suddenly, QList<QVariant>'s symbols are exported from two libraries - /clash/.class Q_EXPORT Y: public QList<QVariant> {};
- Don't mix const and non-const iterators. This will silently crash on broken compilers.
- 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 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.
- Use the static keyword with local functions, even inside anonymous namespaces. Rationale: `static` is attached to individual functions, not a scope of uncertain extent. This helps to understand the context when working on unfamiliar code.
for (Container::const_iterator it = c.begin(); it != c.end(); ++it) // W R O N G
for (Container::const_iterator it = c.cbegin(); it != c.cend(); ++it) // Right
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: https://community.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.
Operators
"The decision between member and non-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.
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:
class B: public A { using A::val; int val(int x); };
- 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:
- 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) && (Foo == 0) // Right #if Foo - 0 == 0 // Clever, are we? Use the one above instead, for better readability
Conventions for C++11 usage
Note: This section is not an accepted convention yet. This section serves as baseline for further discussions.
Lambdas
You can use lambdas with the following restrictions:
- If you use static functions from the class that the lambda is located in, refactor the code so you don't use a lambda. For example, instead of
void Foo::something() { ... std::generate(begin, end, []() { return Foo::someStaticFunction(); }); ... }
You may be able to simply pass the function pointer:
void Foo::something() { ... std::generate(begin, end, &Foo::someStaticFunction); ... }
The reason for this is that GCC 4.7 and earlier had a bug that required capturing this but Clang 5.0 and later will produce a warning if you do:
void Foo::something() { ... std::generate(begin, end, [this]() { return Foo::someStaticFunction(); }); // warning: lambda capture 'this' is not used [-Wunused-lambda-capture] ... }
Format the lambda according to the following rules:
- Always write parentheses for the parameter list, even if the function does not take parameters.
[]() { doSomething(); }
-NOT
[] { doSomething(); }
- Place the capture-list, parameter list, return type, and opening brace on the first line, the body indented on the following lines, and the closing brace on a new line.
[]() -> bool { something(); return isSomethingElse(); }
-NOT-
[]() -> bool { something(); somethingElse(); }
- Place a closing parenthesis and semicolon of an enclosing function call on the same line as the closing brace of the lambda.
foo([]() { something(); });
- If you are using a lambda in an 'if' statement, start the lambda on a new line, to avoid confusion between the opening brace for the lambda and the opening brace for the 'if' statement.
if (anyOf(fooList, [](Foo foo) { return foo.isGreat(); })) { return; }
-NOT-
if (anyOf(fooList, [](Foo foo) { return foo.isGreat(); })) { return; }
- Optionally, place the lambda completely on one line if it fits.
foo([]() { return true; }); if (foo([]() { return true; })) { ... }
auto Keyword
Optionally, you can use the auto keyword in the following cases. If in doubt, for example if using auto could make the code less readable, do not use auto. Keep in mind that code is read much more often than written.
- When it avoids repetition of a type in the same statement.
auto something = new MyCustomType; auto keyEvent = static_cast<QKeyEvent *>(event); auto myList = QStringList() << QLatin1String("FooThing") << QLatin1String("BarThing");
- When assigning iterator types.
auto it = myList.const_iterator();