Qt Creator Coding Rules | Extending Qt Creator Manual

- Extending Qt Creator Manual
- Qt Creator Coding Rules
- Extending Qt Creator Manual 13.0.1

User Interface Text Guidelines ◦ Qt Creator API Reference

# Qt Creator Coding Rules

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:

- The most important rule is: KISS (keep it short and simple). Always choose the simpler implementation option over the more complicated one. This makes maintenance a lot easier.
- Write good C++ code. That is, readable, well commented when necessary, and object-oriented.
- Take advantage of Qt. Do not re-invent the wheel. Think about which parts of your code are generic enough that they might be incorporated into Qt instead of Qt Creator.
- Adapt the code to the existing structures in Qt Creator. If you have improvement ideas, discuss them with other developers before writing the code.
- Follow the guidelines in Code Constructs, Formatting, and Patterns and Practices.
- Document interfaces. Right now we use qdoc, but changing to doxygen is being considered.

## Submitting Code

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 Qt Contribution Guidelines.

## Binary and Source Compatibility

The following list describes how the releases are numbered and defines binary compatibility and source code compatibility between releases:

- Qt Creator 3.0.0 is a major release, Qt Creator 3.1.0 is a minor release, and Qt Creator 3.1.3 is a patch release.
- Backward binary compatibility means that code linked to an earlier version of the library still works.
- Forward binary compatibility means that code linked to a newer version of the library works with an older library.
- Source code compatibility means that code compiles without modification.

We do not currently guarantee binary nor source code compatibility between major releases and minor releases.

However, we try to preserve backward binary compatibility and backward source code compatibility for patch releases within the same minor release:

- Soft API freeze: Starting shortly after the beta release of a minor release, we start keeping backward source code compatibility within that minor release, including its patch releases. This means that from that point, code that uses Qt Creator API will compile against the API of all coming versions of this minor release, including its patch releases. There still might be occasional exceptions to this rule, which should be properly communicated.
- Hard API freeze: Starting with the release candidate of a minor release, we keep backward source code compatibility within that minor release, including its patch releases. We also start keeping backward binary compatibility, with the exception that this will not be reflected in the plugins' compatVersion setting. So, Qt Creator plugins written against the release candidate will not actually load in the final release or later versions, even though the binary compatibility of the libraries would theoretically allow for it. See the section about plugin specs below.
- Hard ABI freeze: Starting with the final release of a minor release, we keep backward source code and binary compatibility for this release and all its patch releases.

For preserving backward compatibility:

- Do not add or remove any public API (for example global functions, public/protected/private member functions).
- Do not reimplement functions (not even inlines, nor protected or private functions).
- Check Binary Compatibility Workarounds for ways to preserve binary compatibility.

For more information on binary compatibility, see Binary Compatibility Issues With C++.

From the viewpoint of plugin metadata this means that:

- Qt Creator plugins in patch releases will have the minor release as `compatVersion`. For example the plugins from version 3.1.2 will have `compatVersion="3.1.0"`.
- Pre-releases of the minor release, including the release candidate, will still have themselves as the `compatVersion`, meaning that plugins compiled against the final release will not load in the pre-releases.
- Qt Creator plugin developers can decide if their plugin requires a certain patch release (or later) of other Qt Creator plugins, or if they work with all patch releases of this minor version, by setting the corresponding `version` when declaring the dependency on the other plugin. The default for Qt Creator plugins provided by the Qt Project is to require the latest patch release.

For example, the `Find` plugin in Qt Creator 3.1 beta (internal version number 3.0.82) will have

     <plugin name="Find" version="3.0.82" compatVersion="3.0.82">
       <dependencyList>
         <dependency name="Core" version="3.0.82"/>
         ....

The `Find` plugin in Qt Creator 3.1.0 final will have

     <plugin name="Find" version="3.1.0" compatVersion="3.1.0">
       <dependencyList>
         <dependency name="Core" version="3.1.0"/>
         ....

The `Find` plugin in Qt Creator 3.1.1 patch release will have version 3.1.1, will be backward binary compatible with `Find` plugin version 3.1.0 (`compatVersion="3.1.0"`), and will require a `Core` plugin that is binary backward compatible with `Core` plugin version 3.1.1:

     <plugin name="Find" version="3.1.1" compatVersion="3.1.0">
       <dependencyList>
         <dependency name="Core" version="3.1.1"/>
         ....

## Code Constructs

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++.

- Prefer preincrement to postincrement whenever possible. Preincrement is potentially faster than postincrement. Just think about the obvious implementations of pre/post-increment. This rule applies to decrement too:

       ++T;
       --U;

       -NOT-

       T++;
       U--;

- Try to minimize evaluation of the same code over and over. This is aimed especially at loops:

       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) {
               ...;
       }

## Formatting

### Capitalizing Identifiers

Use camel case in identifiers.

Capitalize the first word in an identifier as follows:

- Class names begin with a capital letter.
- Function names begin with a lower case letter.
- Variable names begin with a lower case letter.
- Enum names and values begin with a capital letter. Unscoped Enum values contain some part of the name of the enum type.

### Whitespace

- Use four spaces for indentation, no tabs.
- Use blank lines to group statements together where suited.
- Always use only one blank line.

#### Pointers and References

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.

#### Operator Names and Parentheses

Do not use spaces between operator names and parentheses. The equation marks (==) are a part of the operator name, and therefore, spaces make the declaration look like an expression:

     operator==(type)

     -NOT-

     operator == (type)

#### Function Names and Parentheses

Do not use spaces between function names and parentheses:

     void mangle()

     -NOT-

     void mangle ()

#### Keywords

Always use a single space after a keyword, and before a curly brace:

     if (foo) {
     }

     -NOT-

     if(foo){
     }

#### Comments

In general, put one space after "//". To align text in multiline comments, you can insert multiple spaces.

### Braces

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);

### Parentheses

Use parentheses to group expressions:

     if ((a && b) || c)

     -NOT-

     if (a && b || c)

     (a + b) & c

     -NOT-

     a + b & c

### Line Breaks

- Keep lines shorter than 100 characters.
- Insert line breaks if necessary.
- Commas go at the end of a broken line.
- Operators start at the beginning of the new line.

       if (longExpression
           || otherLongExpression
           || otherOtherLongExpression) {
       }

       -NOT-

       if (longExpression ||
           otherLongExpression ||
           otherOtherLongExpression) {
       }

### Declarations

- Use this order for the access sections of your class: public, protected, private. The public section is interesting for every user of the class. The private section is only of interest for the implementors of the class (you).
- Avoid declaring global objects in the declaration file of the class. If the same variable is used for all objects, use a static member.
- Use `class` instead of `struct`. Some compilers mangle that difference into the symbol names and spit out warnings if a struct declaration is followed by a class definition. To avoid ongoing changes from one to the other we declare `class` the preferred way.

#### Declaring Variables

- Avoid global variables of class type to rule out initialization order problems. Consider using `Q_GLOBAL_STATIC` if they cannot be avoided.
- Declare global string literals as

       const char aString[] = "Hello";

- Avoid short names (such as, a, rbarr, nughdeget) whenever possible. Use single-character variable names only for counters and temporaries, where the purpose of the variable is obvious.
- Declare each variable on a separate line:

       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.

- Avoid abbreviations:

       int height;
       int width;
       char *nameOfThis;
       char *nameOfThat;

       -NOT-

       int a, b;
       char *c, *d;

- Wait with declaring a variable until it is needed. This is especially important when initialization is done at the same time.

### Namespaces

- Put the left curly brace on the same line as the `namespace` keyword.
- Do not indent declarations or definitions inside.
- Optional, but recommended if the namespaces spans more than a few lines: Add a comment after the right curly brace repeating the namespace.

       namespace MyPlugin {

       void someFunction() { ... }

           }  // namespace MyPlugin

- As an exception, if there is only a single class declaration inside the namespace, all can go on a single line:

       namespace MyPlugin { class MyClass; }

- Do not use using-directives in header files.
- Do not rely on using-directives when defining classes and functions, instead define it in a properly named declarative region.
- Do not rely on using-directives when accessing global functions.
- In other cases, you are encouraged to use using-directives, as they help you avoid cluttering the code. Prefer putting all using-directives near the top of the file, after all includes.

       [in foo.cpp]
       ...
       #include "foos.h"
       ...
       #include <utils/filename.h>
       ...
       using namespace Utils;

       namespace Foo::Internal {

       void SomeThing::bar()
       {
           FilePath f;              // or Utils::FilePath f
           ...
       }
       ...
       } // Foo::Internal           // or // namespace Foo::Internal

       -NOT-

       [in foo.h]
       ...
       using namespace Utils;       // Wrong: no using-directives in headers

       class SomeThing
       {
           ...
       };

       -NOT-

       [in foo.cpp]
       ...
       using namespace Utils;

       #include "bar.h"             // Wrong: #include after using-directive

       -NOT-

       [in foo.cpp]
       ...
       using namepace Foo;

       void SomeThing::bar()        // Wrong if Something is in namespace Foo
       {
           ...
       }

## Patterns and Practices

### Namespacing

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:

- Classes/Symbols of a library or plugin that are exported for use of other libraries or plugins are in a namespace specific to that library/plugin, e.g. `MyPlugin`.
- Classes/Symbols of a library or plugin that are not exported are in an additional `Internal` namespace, e.g. `MyPlugin::Internal`.

### Passing File Names

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. Consider using Utils::FilePath::fromUserInput(QString) and Utils::FilePath::toUserOutput() for these tasks.

Use Utils::FilePath when comparing file names, because that takes case sensitivity into account. Also make sure that you compare clean paths (QDir::cleanPath()).

### Classes to Use and Classes Not to Use

A significant portion of Qt Creator code handles data on devices that are not the same as the development machine. These may differ in aspects like path separator, line endings, process launching details and so on.

However, some basic Qt classes assume that a Qt application is only concerned with machines that are similar to the development machine.

These classes are therefore not appropriate to use in the part of Qt Creator that is concerned with non-local code. Instead, Qt Creator's Utils library provides substitutes, leading to the following rules:

- Use Utils::FilePath for any QString that semantically is a file or directory, see also Passing File Names.
- Prefer using Utils::FilePath over any use of QDir and QFileInfo.
- Prefer using Utils::QtcProcess over QProcess.
- If Utils::FilePath or Utils::QtcProcess functionality is not sufficient for your purpose, prefer enhancing them over falling back to QString or QProcess.
- Avoid platform #ifdefs unless they are absolutely needed for locally executed code, and even then prefer Utils::HostInfo over #ifdefs.

### Plugin Dependencies

To keep Qt Creator scalable we aim at keeping hard run-time dependencies between plugins and to external libraries as few as reasonably possible.

There are several techniques for that.

### Extending Base Plugin Functionality by Callbacks

This pattern allows leaf plugins to provide additional functionality to a central plugin by injecting a callback.

It is used for functionality that is helpful in some setups but not applicable or considered intrusive (e.g. because of size or external dependencies) in others, so that users may want to enable or disable it without impacting the rest of their setup.

The leaf plugin can then for example depend on a large (or otherwise inconvenient) external dependency without imposing this dependency on the central plugin.

The overall pattern looks like:

- In `centralplugin/somewhere.h`

       std::function<void(...)> &fancyLeafCallback();

       void possiblyFancyOperation();

- In `centralplugin/somewhere.cpp`

       std::function<void(...)> &fancyLeafCallback()
       {
           static std::function<void(...)> callback;
           return callback;
       }
       ...

       void possiblyFancyOperation()
       {
          if (auto callback = fancyLeafCallback()) {
             // can be used
             callback();
          } else {
             // not present, use some plain fallback implementation
             // or error out
          }
       }

- In `leafplugin/leafplugin.cpp`:

       void LeafPlugininitialize()
       {
          ...
          Central::fancyLeafCallback() = [this](...) { doSomething; };
          ...
       }

### Plugin Extension Points

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.

### Using the Global Object Pool

You can add objects to the global object pool via ExtensionSystem::PluginManager::addObject(), and retrieve objects of a specific type again via ExtensionSystem::PluginManager::getObject(). 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.

### C++ Features

- Prefer `#pragma once` over header guards.
- Do not use exceptions, unless you know what you do.
- Do not use RTTI (Run-Time Type Information; that is, the typeinfo struct, the dynamic_cast or the typeid operators, including throwing exceptions), unless you know what you do.
- Do not use virtual inheritance, unless you know what you do.
- 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.

- 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 locale you want your string in) or \xnn (where nn is hexadecimal). For example: QString s = QString::fromUtf8("\213\005");
  - For umlauts in documentation, or other non-ASCII characters, either use the qdoc `\unicode` command or use the relevant macro. For example: `\uuml` for ü.
- Use static keywords instead of anonymous namespaces whenever 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 (ISO/IEC 14882, 7.1.1/6, or see various discussions about this on the gcc mailing lists).

#### Null Pointers

Use nullptr for null pointer constants.

     void *p = nullptr;

     -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 or 0.

#### Lambdas

Format the lambda according to the following rules:

- When the lambda neither takes arguments nor specifies a return type, drop round brackets.

       [] { ... lambda body ... }

       -NOT-

       []() { ... lambda body ... }

- Glue square brackets with round brackets when defining a lambda.

       [](int a) { ... lambda body ... }

       -NOT-

       [] (int a) { ... lambda body ... }

- 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({ "FooThing",  "BarThing" });

- When assigning iterator types.

       auto it = myList.const_iterator();

#### Scoped enums

You can use scoped enums in places where the implicit conversion to int of unscoped enums is undesired or the additional scope is useful.

#### Delegating constructors

Use delegating constructors if multiple constructors use essentially the same code.

#### Initializer list

Use initializer lists to initialize containers, for example:

     const QList<int> values = {1, 2, 3, 4, 5};

#### Initialization with Curly Brackets

If you use initialization with curly brackets, follow the same rules as with round brackets. For example:

     class Values // the following code is quite useful for test fixtures
     {
         float floatValue = 4; // prefer that for simple types
         QList<int> values = {1, 2, 3, 4, integerValue}; // prefer that syntax for initializer lists
         SomeValues someValues{"One", 2, 3.4}; // not an initializer_list
         SomeValues &someValuesReference = someValues;
         ComplexType complexType{values, otherValues} // constructor call
     }

     object.setEntry({"SectionA", value, doubleValue}); // calls a constructor
     object.setEntry({}); // calls default constructor

But be careful not to overuse it, to not obfuscate your code.

#### Non-Static Data Member Initialization

Use non-static data member initialization for trivial initializations, except in public exported classes.

#### Defaulted and Deleted Functions

Consider using `=default` and `=delete` to control the special functions.

#### Override

It is recommended to use the `override` keyword when overriding virtual functions. Do not use virtual on overridden functions.

Make sure that a class uses `override` consistently, either for all overridden functions or for none.

#### Range-Based for-Loop

You may use range-based for-loops, but beware of the spurious detachment problem. If the for-loop only reads the container and it is not obvious whether the container is const or unshared, use `std::cref()` to ensure that the container is not unnecessarily detached.

#### std::optional

Avoid the throwing function `value()`. Check the availability of the value first, and then use the non-throwing functions for accessing values, like `operator*` and `operator->`. In very simple cases, you can also use `value_or()`.

     if (optionalThing) {
         val = optionalThing->member;
         other = doSomething(*optionalThing);
     }

     -NOT-

     if (optionalThing) {
         val = optionalThing.value().member;
         other = doSomething(optionalThing.value());
     }

### Using QObject

- Remember to add the Q_OBJECT macro to QObject subclasses that rely on the meta object system. Meta object system related features are the definition of signals and slots, the use of `qobject_cast<>`, and others. See also Casting.
- Prefer Qt5-style `connect()` calls over Qt4-style.
- When using Qt4-style `connect()` calls, normalize the arguments for signals and slots inside connect statements to safely make signal and slot lookup a few cycles faster. You can use $QTDIR/util/normalize to normalize existing code. For more information, see QMetaObject::normalizedSignature.
- Avoid using `QObject::sender()`. Pass the sender explicitly instead.

       connect(action, &QAction::triggered, this, [this, action] {
           onActionTriggered(action);
       });
       ...
       void MyClass::onActionTriggered(QAction *action)
       {
           ... use action ...
       }

       -NOT-

       connect(action, &QAction::triggered, this, &MyClass::onActionTriggered);
       ...
       void MyClass::onActionTriggered()
       {
           QAction *action = qobject_cast<QAction *>(sender());
           if (action == nullptr)
               return;

           ... use action ...
       }

- Avoid `QSignalMapper`. Use a lambda instead and pass the mapped value via the lambda capture.

### File Headers

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.

### Including Headers

- Use the following format to include Qt headers: `#include <QWhatEver>`. Do not include the module as it might have changed between Qt4 and Qt5.
- Arrange includes in an order that goes from specific to generic to ensure that the headers are self-contained. For example:
  - `#include "myclass.h"`
  - `#include "otherclassinplugin.h"`
  - `#include <otherplugin/someclass.h>`
  - `#include <QtClass>`
  - `#include <stdthing>`
  - `#include <system.h>`
- Enclose headers from other plugins in angle brackets (<>) rather than quotation marks ("") to make it easier to spot external dependencies in the sources.
- Add empty lines between long blocks of peer headers and try to arrange the headers in alphabetic order within a block.

### Casting

- Avoid C casts, prefer C++ casts (`static_cast`, `const_cast`, `reinterpret_cast`) Both `reinterpret_cast` and C-style casts are dangerous, but at least `reinterpret_cast` will not remove the const modifier.
- Do not use `dynamic_cast`, use `qobject_cast` for QObjects, or refactor your design, for example by introducing a `type()` function (see QListWidgetItem), unless you know what you do.

### Compiler and Platform-specific Issues

- Be extremely careful when using the question mark operator. If the returned types are not identical, some compilers generate code that crashes at runtime (you will not even get a compiler warning):

       QString s;
       // crash at runtime - QString vs. const char *
       return condition ? s : "nothing";

- 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 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;
       };

- Stick to integral types, arrays of integral types, and structs thereof for static declarations in headers. For example, `static float i[SIZE_CONSTANT];` will not be optimized and copied in every plugin in most cases, it would be good to avoid it.
- 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 or 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 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_GLOBAL_STATIC(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.

- A `char` is signed or unsigned dependent on the architecture. Use signed `char` or `uchar` if you explicitly want a signed or unsigned char. The following code will break on PowerPC, for example:

       // Condition is always true on platforms where the
       // default is unsigned:
       if (c >= 0) {
           ...
       }

- Avoid 64-bit enum values. The AAPCS (Procedure Call Standard for the ARM Architecture) embedded ABI hard codes all enum values to a 32-bit integer.
- Do not mix const and non-const iterators. This will silently crash on broken compilers.

       for (Container::const_iterator it = c.constBegin(); it != c.constEnd(); ++it)

       -NOT-

       for (Container::const_iterator it = c.begin(); it != c.end(); ++it)

- Do not inline virtual destructors in exported classes. This leads to duplicated vtables in dependent plugins and this can also break RTTI. See QTBUG-45582.

### Esthetics

- Prefer unscoped enums to define const over static const int or defines. Enumeration values will be replaced by the compiler at compile time, resulting in faster code. Defines are not namespace safe.
- Prefer verbose argument names in headers. Qt Creator will show the argument names in their completion box. It will look better in the documentation.

### Inheriting from Template or Tool Classes

Inheriting from template or tool classes has the following potential pitfalls:

- The destructors are not virtual, which can lead to memory leaks.
- The symbols are not exported (and mostly inline), which can lead to symbol clashes.

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.

### Inheritance Versus Aggregation

- Use inheritance if there is a clear is-a relation.
- Use aggregation for re-use of orthogonal building blocks.
- Prefer aggregation over inheritance if there is a choice.

### 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`. For more information, see Casting.
- 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, or, preferred, move such code into an implementation file.
- Do not hide virtual functions 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)`, the A `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
       };

- Do not shadow variables (`-Wshadow`).
- Avoid things like `this->x = x;` if possible.
- Do not give variables the same name as functions declared in your class.
- To improve code readability, always check whether a preprocessor variable is defined before probing its value (`-Wundef`).

       #if defined(Foo) && Foo == 0

         -NOT-

       #if Foo == 0

       -NOT-

       #if Foo - 0 == 0

- When checking for a preprocessor define using the `defined` operator, always include the variable name in parentheses.

       #if defined(Foo)

         -NOT-

         #if defined Foo

## Class Member Names

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();
         ~Bar();
         int value() const;

         QScopedPointer<BarPrivate> d;
         //std::unique_ptr<BarPrivate> d;
     };

     ############### bar.cpp

     #include "bar.h"

     struct BarPrivate { BarPrivate() : i(23) {} int i; };

     Bar::Bar() : d(new BarPrivate) {}

     Bar::~Bar() {}

     int Bar::value() const { return d->i; }

     ############### baruser.cpp

     #include "bar.h"

     int barUser() { Bar b; return b.value(); }

     ############### baz.h

     struct BazPrivate;

     struct Baz
     {
         Baz();
         ~Baz();
         int value() const;

         BazPrivate *d;
     };

     ############### baz.cpp

     #include "baz.h"

     struct BazPrivate { BazPrivate() : i(23) {} int i; };

     Baz::Baz() : d(new BazPrivate) {}

     Baz::~Baz() { delete d; }

     int Baz::value() const { return d->i; }

     ############### bazuser.cpp

     #include "baz.h"

     int bazUser() { Baz b; return b.value(); }

     ############### main.cpp

     int barUser();
     int bazUser();

     int main() { return barUser() + bazUser(); }

Results:

     Object file size:

      14428 bar.o
       4744 baz.o

       8508 baruser.o
       2952 bazuser.o

     Symbols in bar.o:

         00000000 W _ZN3Foo10BarPrivateC1Ev
         00000036 T _ZN3Foo3BarC1Ev
         00000000 T _ZN3Foo3BarC2Ev
         00000080 T _ZN3Foo3BarD1Ev
         0000006c T _ZN3Foo3BarD2Ev
         00000000 W _ZN14QScopedPointerIN3Foo10BarPrivateENS_21QScopedPointerDeleterIS2_EEEC1EPS2_
         00000000 W _ZN14QScopedPointerIN3Foo10BarPrivateENS_21QScopedPointerDeleterIS2_EEED1Ev
         00000000 W _ZN21QScopedPointerDeleterIN3Foo10BarPrivateEE7cleanupEPS2_
         00000000 W _ZN7qt_noopEv
                  U _ZN9qt_assertEPKcS1_i
         00000094 T _ZNK3Foo3Bar5valueEv
         00000000 W _ZNK14QScopedPointerIN3Foo10BarPrivateENS_21QScopedPointerDeleterIS2_EEEptEv
                  U _ZdlPv
                  U _Znwj
                  U __gxx_personality_v0

     Symbols in baz.o:

         00000000 W _ZN3Foo10BazPrivateC1Ev
         0000002c T _ZN3Foo3BazC1Ev
         00000000 T _ZN3Foo3BazC2Ev
         0000006e T _ZN3Foo3BazD1Ev
         00000058 T _ZN3Foo3BazD2Ev
         00000084 T _ZNK3Foo3Baz5valueEv
                  U _ZdlPv
                  U _Znwj
                  U __gxx_personality_v0

## Documentation

The documentation is generated from source and header files. You document for the other developers, not for yourself. In the header files, document interfaces. That is, what the function does, not the implementation.

In the .cpp files, you can document the implementation if the implementation is not obvious.

User Interface Text Guidelines ◦ Qt Creator API Reference