Coding Conventions: Difference between revisions
(Add first C++11 guidelines. Right now it is not binding and merely serves as discussion point.) |
(fixed markup) |
||
Line 1: | Line 1: | ||
[[Category:Developing_Qt::Guidelines]] | [[Category:Developing_Qt::Guidelines]] | ||
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. | ||
Line 27: | Line 23: | ||
=== Including headers === | === Including headers === | ||
<ul> | |||
<li>In public header files, always use this form to include Qt headers: <tt>#include <QtCore/qwhatever.h></tt>. The library prefix is neccessary for Mac OS X frameworks and is very convenient for non-qmake projects. | |||
</li> | |||
<li>In source files, include specialized headers first, then generic headers. Separate the categories with empty lines. | |||
<code> | <code> | ||
Line 37: | Line 37: | ||
#include <limits.h> // system stuff | #include <limits.h> // system stuff | ||
</code> | </code> | ||
</li> | |||
<li>If you need to include <tt>qplatformdefs.h</tt>, always include it as the '''first''' header file. | |||
</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. | |||
<code> | <code> | ||
#include <private/whatever_p.h> | #include <private/whatever_p.h> | ||
</code> | </code> | ||
</li> | |||
<li>If you need to include <tt>qt_x11_p.h</tt>, always include it as the '''last''' header file. | |||
</li> | |||
</ul> | |||
=== Casting === | === Casting === | ||
Line 57: | Line 64: | ||
=== Compiler/Platform specific issues === | === Compiler/Platform specific issues === | ||
<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). | |||
<code> | <code> | ||
Line 63: | Line 72: | ||
return condition ? s : "nothing"; // crash at runtime - QString vs. const char * | return condition ? s : "nothing"; // crash at runtime - QString vs. const char * | ||
</code> | </code> | ||
</li> | |||
<li>Be extremely careful about alignment. | |||
<ul> | |||
<li>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 <tt>const char *</tt> is cast to an <tt>const int *</tt>, it'll crash on machines where integers have to be aligned at a two- or four-byte boundaries. | |||
</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. | |||
<code> | <code> | ||
Line 74: | Line 88: | ||
}; | }; | ||
</code> | </code> | ||
</li> | |||
</ul> | |||
</li> | |||
<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: | |||
<code> | <code> | ||
Line 92: | Line 109: | ||
static int y = 7; // Works - y will be 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 MyStruct s = {1, 2, 3}; // Works - will be initialized statically, no code being run | ||
static QString | static QString *ptr = 0; // Pointers to objects are ok - no code needed to be run to initialize ptr | ||
</code> | </code> | ||
Use <tt>Q_GLOBAL_STATIC</ | Use <tt>Q_GLOBAL_STATIC</tt> to create static global objects instead: | ||
<code> | <code> | ||
Line 107: | Line 124: | ||
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. | 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. | ||
</li> | |||
<li>A <tt>char</tt> is signed or unsigned dependent on the architecture. Use <tt>signed char</tt> or <tt>uchar</tt> if you explicitely want a signed/unsigned char. The following code will break on ppc, for example: | |||
<code> | <code> | ||
char c = 'A'; | char c = 'A'; | ||
if (c < 0) { … } // WRONG- condition is always true on platforms where the default is unsigned char | if (c < 0) { … } // WRONG - condition is always true on platforms where the default is unsigned char | ||
</code> | </code> | ||
</li> | |||
<li>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) | |||
</li> | |||
</ul> | |||
=== Aesthetics === | === Aesthetics === | ||
Line 128: | Line 150: | ||
** 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. | * When reimplementing a virtual method, do not put the `virtual` keyword in the header file. <br /> | ||
On Qt5, annotate them with the [http://doc.qt.io/qt-5.0/qtcore/qtglobal.html#Q_DECL_OVERRIDE Q_DECL_OVERRIDE] macro after the function declaration, just before the ';' (or the '{' ). | On Qt5, annotate them with the [http://doc.qt.io/qt-5.0/qtcore/qtglobal.html#Q_DECL_OVERRIDE Q_DECL_OVERRIDE] macro after the function declaration, just before the ';' (or the '{' ). | ||
=== Things to avoid === | === Things to avoid === | ||
<ul> | |||
<li>Do not inherit from template/tool classes | |||
<ul> | |||
<li>The destructors are not virtual, leading to potential memory leaks | |||
</li> | |||
<li>The symbols are not exported (and mostly inline), leading to interesting symbol clashes. | |||
</li> | |||
<li>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/. | |||
</li> | |||
</ul> | |||
</li> | |||
<li>Don't mix const and non-const iterators. This will silently crash on broken compilers. | |||
<code> | <code> | ||
for (Container::const_iterator it = c.begin(); it != c.end(); + | 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 | for (Container::const_iterator it = c.constBegin(); it != c.constEnd(); ++it) // Right | ||
</code> | </code> | ||
</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: | |||
<code> | <code> | ||
Line 154: | Line 186: | ||
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>Avoid the use of anonymous namespaces in favor of the static keyword if possible. A name localized to the compilation unit with <tt>static</tt> 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) | |||
</li> | |||
</ul> | |||
=== Binary and Source Compatibility === | === Binary and Source Compatibility === | ||
Line 164: | Line 200: | ||
** 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 [[ | ** Check [[Binary Compatibility Workarounds]] for ways to keep b/c | ||
* Info on binary compatibility: http://techbase.kde.org/Policies/Binary_Compatibility_Issues_With_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. | * 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. | |||
=== Operators === | === Operators === | ||
[http://stackoverflow.com/questions/4421706/operator-overloading/4421729#4421729 "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. | 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 204: | Line 235: | ||
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: | ||
<ul> | |||
<li>No C style casts (<tt>-Wold-style-cast</tt>) | |||
* 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 | |||
</li> | |||
<li>No float comparisons (<tt>-Wfloat-equal</tt>) | |||
* 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. | |||
</li> | |||
<li>Don't hide virtual methods in subclasses (<tt>-Woverloaded-virtual</tt>) | |||
<ul> | |||
<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, and add the following silly workaround for broken compilers: | |||
<code> | <code> | ||
Line 226: | Line 259: | ||
}; | }; | ||
</code> | </code> | ||
</li> | |||
</ul> | |||
</li> | |||
<li>Don't shadow variables (<tt>-Wshadow</tt>) | |||
* avoid things like <tt>this->x = x;</tt> | |||
* don't give variables the same name as functions declared in your class | |||
</li> | |||
<li>Always check whether a preprocessor variable is defined before probing its value (<tt>-Wundef</tt>) | |||
<code> | <code> | ||
#if Foo | #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 | #if Foo - 0 == 0 // Clever, are we? Use the one above instead, for better readability | ||
</code> | </code> | ||
</li> | |||
</ul> | |||
== Conventions for C++11 usage == | == Conventions for C++11 usage == | ||
Line 247: | Line 287: | ||
You can use lambdas with the following restrictions: | You can use lambdas with the following restrictions: | ||
<ul> | |||
<li>You have to explicitly specify the return type, if the lambda contains more than a single expression. Otherwise it does not compile with VS2010. | |||
<code> | <code> | ||
[]() -> QString { | []() -> QString { | ||
Line 261: | Line 303: | ||
}); | }); | ||
</code> | </code> | ||
</li> | |||
<li>If you use static functions from the class that the lambda is located in, you have to explicitly capture this. Otherwise it does not compile with g++ 4.7 and earlier. | |||
<code> | <code> | ||
Line 281: | Line 324: | ||
} | } | ||
</code> | </code> | ||
</li> | |||
</ul> | |||
Format the lambda according to the following rules: | Format the lambda according to the following rules: | ||
<ul> | |||
<li>Always write parentheses for the parameter list, even if the function does not take parameters. | |||
<code> | <code> | ||
Line 293: | Line 341: | ||
[] { doSomething(); } | [] { doSomething(); } | ||
</code> | </code> | ||
</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. | |||
<code> | <code> | ||
Line 307: | Line 356: | ||
somethingElse(); } | somethingElse(); } | ||
</code> | </code> | ||
</li> | |||
<li>Place a closing parenthesis and semicolon of an enclosing function call on the same line as the closing brace of the lambda. | |||
<code> | <code> | ||
Line 315: | Line 365: | ||
}); | }); | ||
</code> | </code> | ||
</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. | |||
<code> | <code> | ||
Line 334: | Line 385: | ||
} | } | ||
</code> | </code> | ||
</li> | |||
<li>Optionally, place the lambda completely on one line if it fits. | |||
<code> | <code> | ||
Line 344: | Line 396: | ||
} | } | ||
</code> | </code> | ||
</li> | |||
</ul> | |||
=== auto Keyword === | === auto Keyword === | ||
Line 349: | Line 404: | ||
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. | ||
<ul> | |||
<li>When it avoids repetition of a type in the same statement. | |||
<code> | <code> | ||
auto something = new MyCustomType; | auto something = new MyCustomType; | ||
Line 355: | Line 412: | ||
auto myList = QStringList() << QLatin1String("FooThing") << QLatin1String("BarThing"); | auto myList = QStringList() << QLatin1String("FooThing") << QLatin1String("BarThing"); | ||
</code> | </code> | ||
</li> | |||
<li>When assigning iterator types. | |||
<code> | <code> | ||
auto it = myList.const_iterator(); | auto it = myList.const_iterator(); | ||
</code> | </code> | ||
</li> | |||
</ul> |
Revision as of 15:25, 27 February 2015
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 \nnn (where nnn is the octal representation of whatever character encoding you want your string in) or \xnn (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 ü
- 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. Use the following syntax, irrespective of 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 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 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.
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 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 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.
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, 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 };
- 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:
- 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:
- You have to explicitly specify the return type, if the lambda contains more than a single expression. Otherwise it does not compile with VS2010.
[]() -> QString { Foo *foo = activeFoo(); return foo ? foo->displayName() : QString(); }); -NOT- []() { Foo *foo = activeFoo(); return foo ? foo->displayName() : QString(); });
- If you use static functions from the class that the lambda is located in, you have to explicitly capture this. Otherwise it does not compile with g++ 4.7 and earlier.
void Foo::something() { ... [this]() { Foo::someStaticFunction(); } ... } -NOT- void Foo::something() { ... []() { Foo::someStaticFunction(); } ... }
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();