[Previous: User Interface Text Guidelines] [Next: Qt Creator API Reference]
Note: This document is work in progress.
The coding rules aim to guide Qt Creator developers, to help them write understandable and maintainable code, and to minimize confusion and surprises.
As usual, rules are not set in stone. If you have a good reason to break one, do so. But first make sure that at least some other developers agree with you.
To contribute to the main Qt Creator source, you should comply to the following rules:
To submit code to Qt Creator, you must understand the tools and mechanics as well as the philosophy behind Qt development. For more information about how to set up the development environment for working on Qt Creator and how to submit code and documentation for inclusion, see Guidelines for Contributions to the Qt Project.
The following list describes how the releases are numbered and defines binary compatibility and source code compatibility between releases:
We do not currently guarantee API nor ABI (application binary interface) compatibility between major releases and minor releases.
However, we try to preserve backward and forward binary compatibility and forward and backward source code compatibility in patch releases, so:
Note: This is not yet mandatory.
For more information on binary compatibility, see Binary Compatibility Issues With C++.
Follow the guidelines for code constructs to make the code faster and clearer. In addition, the guidelines allow you to take advantage of the strong type checking in C++.
++T; --U; -NOT- T++; U--;
Container::iterator end = large.end(); for (Container::iterator it = large.begin(); it != end; ++it) { ...; } -NOT- for (Container::iterator it = large.begin(); it != large.end(); ++it) { ...; }
foreach (QWidget *widget, container) doSomething(widget); -NOT- Container::iterator end = container.end(); for (Container::iterator it = container.begin(); it != end; ++it) doSomething(*it);
Make the loop variable const, if possible. This might prevent unnecessary detaching of shared data:
foreach (const QString &name, someListOfNames) doSomething(name); - NOT - foreach (QString name, someListOfNames) doSomething(name);
Use camel case in identifiers.
Capitalize the first word in an identifier as follows:
For pointers or references, always use a single space before an asterisk (*) or an ampersand (&), but never after. Avoid C-style casts when possible:
char *blockOfMemory = (char *)malloc(data.size()); char *blockOfMemory = reinterpret_cast<char *>(malloc(data.size())); -NOT- char* blockOfMemory = (char* ) malloc(data.size());
Of course, in this particulare case, using new might be an even better option.
Do not use spaces between operator names and function names. The equation marks (==) are a part of the function name, and therefore, spaces make the declaration look like an expression:
operator==(type) -NOT- operator == (type)
Do not use spaces between function names and parentheses:
void mangle() -NOT- void mangle ()
Always use a single space after a keyword, and before a curly brace:
if (foo) { } -NOT- if(foo){ }
As a base rule, place the left curly brace on the same line as the start of the statement:
if (codec) { } -NOT- if (codec) { }
Exception: Function implementations and class declarations always have the left brace in the beginning of a line:
static void foo(int g) { qDebug("foo: %i", g); } class Moo { };
Use curly braces when the body of a conditional statement contains more than one line, and also if a single line statement is somewhat complex. Otherwise, omit them:
if (address.isEmpty()) return false; for (int i = 0; i < 10; ++i) qDebug("%i", i); -NOT- if (address.isEmpty()) { return false; } for (int i = 0; i < 10; ++i) { qDebug("%i", i); }
Exception 1: Use braces also if the parent statement covers several lines or if it wraps:
if (address.isEmpty() || !isValid() || !codec) { return false; }
Note: This could be re-written as:
if (address.isEmpty()) return false; if (!isValid()) return false; if (!codec) return false;
Exception 2: Use braces also in if-then-else blocks where either the if-code or the else-code covers several lines:
if (address.isEmpty()) { --it; } else { qDebug("%s", qPrintable(address)); ++it; } -NOT- if (address.isEmpty()) --it; else { qDebug("%s", qPrintable(address)); ++it; }
if (a) { if (b) ... else ... } -NOT- if (a) if (b) ... else ...
Use curly braces when the body of a conditional statement is empty:
while (a) {} -NOT- while (a);
Use parentheses to group expressions:
if ((a && b) || c) -NOT- if (a && b || c)
(a + b) & c -NOT- a + b & c
if (longExpression || otherLongExpression || otherOtherLongExpression) { } -NOT- if (longExpression || otherLongExpression || otherOtherLongExpression) { }
const char aString[] = "Hello";
QString a = "Joe"; QString b = "Foo"; -NOT- QString a = "Joe", b = "Foo";
Note: QString a = "Joe" formally calls a copy constructor on a temporary that is constructed from a string literal. Therefore, it is potentially more expensive than direct construction by QString a("Joe"). However, the compiler is allowed to elide the copy (even if this has side effects), and modern compilers typically do so. Given these equal costs, Qt Creator code favours the '=' idiom as it is in line with the traditional C-style initialization, it cannot be mistaken as function declaration, and it reduces the level of nested parantheses in more initializations.
int height; int width; char *nameOfThis; char *nameOfThat; -NOT- int a, b; char *c, *d;
namespace MyPlugin { void someFunction() { ... } } // namespace MyPlugin
namespace MyPlugin { class MyClass; }
Read Qt In Namespace and keep in mind that all of Qt Creator is namespace aware code.
The namespacing policy within Qt Creator is as follows:
Qt Creator API expects file names in portable format, that is, with slashes (/) instead of backslashes (\) even on Windows. To pass a file name from the user to the API, convert it with QDir::fromNativeSeparators first. To present a file name to the user, convert it back to native format with QDir::toNativeSeparators.
When comparing file names, consider using FileManager::fixFileName which makes sure that paths are clean and absolute and also takes Windows case-insensitivity into account (even if it is an expensive operation).
A plugin extension point is an interface that is provided by one plugin to be implemented by others. The plugin then retrieves all implementations of the interface and uses them. That is, they extend the functionality of the plugin. Typically, the implementations of the interface are put into the global object pool during plugin initialization, and the plugin retrieves them from the object pool at the end of plugin initialization.
For example, the Find plugin provides the FindFilter interface for other plugins to implement. With the FindFilter interface, additional search scopes can be added, that appear in the Advanced Search dialog. The Find plugin retrieves all FindFilter implementations from the global object pool and presents them in the dialog. The plugin forwards the actual search request to the correct FindFilter implementation, which then performs the search.
You can add objects to the global object pool via ExtensionSystem::PluginManager::addObject(), and retrieve objects of a specific type again via ExtensionSystem::PluginManager::getObjects(). This should mostly be used for implementations of Plugin Extension Points.
Note: Do not put a singleton into the pool, and do not retrieve it from there. Use the singleton pattern instead.
Hint: Use the compile autotest to see whether a C++ feature is supported by all compilers in the test farm.
\xnn
(where nn is hexadecimal). For example: QString s = QString::fromUtf8("\213\005");Using a plain zero (0) for null pointer constants is always correct and least effort to type.
void *p = 0; -NOT- void *p = NULL; -NOT- void *p = '\0'; -NOT- void *p = 42 - 7 * 6;
Note: As an exception, imported third party code as well as code interfacing the native APIs (src/support/os_*) can use NULL.
If you create a new file, the top of the file should include a header comment equal to the one found in other source files of Qt Creator.
QString s; // crash at runtime - QString vs. const char * return condition ? s : "nothing";
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 a const int *, it will crash on machines where integers have to be aligned at two-byte 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; };
Even if the execution time of the initializer is defined for shared libraries, you will get into trouble when moving that code in a plugin or if the library is compiled statically:
// global scope -NOT- // Default constructor needs to be run to initialize x: static const QString x; -NOT- // Constructor that takes a const char * has to be run: static const QString y = "Hello"; -NOT- QString z; -NOT- // Call time of foo() undefined, might not be called at all: static const int i = foo();
Things you can do:
// global scope // No constructor must be run, x set at compile time: static const char x[] = "someText"; // y will be set at compile time: static int y = 7; // Will be initialized statically, no code being run. static MyStruct s = {1, 2, 3}; // Pointers to objects are OK, no code needed to be run to // initialize ptr: static QString *ptr = 0; // Use Q_GLOBAL_STATIC to create static global objects instead: Q_STATIC_GLOBAL(QString, s) void foo() { s()->append("moo"); }
Note: Static objects in function scope are no problem. The constructor will be run the first time the function is entered. The code is not reentrant, though.
// Condition is always true on platforms where the // default is unsigned: if (c >= 0) { ... }
for (Container::const_iterator it = c.constBegin(); it != c.constEnd(); ++it) -NOT- for (Container::const_iterator it = c.begin(); it != c.end(); ++it)
Inheriting from template or tool classes has the following potential pitfalls:
For example, library A has class Q_EXPORT X: public QList<QVariant> {}; and library B has class Q_EXPORT Y: public QList<QVariant> {};. Suddenly, QList symbols are exported from two libraries which results in a clash.
Our public header files have to survive the strict settings of some of our users. All installed headers have to follow these rules:
class B: public A { #ifdef Q_NO_USING_KEYWORD inline int val() { return A::val(); } #else using A::val; #endif };
#if defined(Foo) && Foo == 0 -NOT- #if Foo == 0 -NOT- #if Foo - 0 == 0
#if defined(Foo) -NOT- #if defined Foo
We use the "m_" prefix convention, except for public struct members (typically in *Private classes and the very rare cases of really public structures). The d and q pointers are exempt from the "m_" rule.
The d pointers ("Pimpls") are named "d", not "m_d". The type of the d pointer in class Foo is FooPrivate *, where FooPrivate is declared in the same namespace as Foo, or if Foo is exported, in the corresponding {Internal} namespace.
If needed (for example when the private object needs to emit signals of the proper class), FooPrivate can be a friend of Foo.
If the private class needs a backreference to the real class, the pointer is named q, and its type is Foo *. (Same convention as in Qt: "q" looks like an inverted "d".)
Do not use smart pointers to guard the d pointer as it imposes a compile and link time overhead and creates fatter object code with more symbols, leading, for instance to slowed down debugger startup:
############### bar.h #include <QScopedPointer> //#include <memory> struct BarPrivate; struct Bar { Bar(); ~<">