coding-style.qdoc 36.7 KB
Newer Older
Leena Miettinen's avatar
Leena Miettinen committed
1 2
/****************************************************************************
**
3
** Copyright (c) 2014 Digia Plc and/or its subsidiary(-ies).
hjk's avatar
hjk committed
4
** Contact: http://www.qt-project.org/legal
Leena Miettinen's avatar
Leena Miettinen committed
5
**
hjk's avatar
hjk committed
6
** This file is part of Qt Creator
Leena Miettinen's avatar
Leena Miettinen committed
7 8 9 10 11 12 13 14 15 16 17 18
**
**
** GNU Free Documentation License
**
** Alternatively, this file may be used under the terms of the GNU Free
** Documentation License version 1.3 as published by the Free Software
** Foundation and appearing in the file included in the packaging of this
** file.
**
**
****************************************************************************/

19
/*!
Leena Miettinen's avatar
Leena Miettinen committed
20
    \previouspage qtcreator-ui-text.html
21
    \page coding-style.html
22
    \nextpage qtcreator-api.html
23

24
    \title Qt Creator Coding Rules
25

26
    \note This document is work in progress.
27

28 29
    The coding rules aim to guide Qt Creator developers, to help them write
    understandable and maintainable code, and to minimize confusion and surprises.
30

31 32
    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.
33

34 35 36 37
    To contribute to the main Qt Creator source, you should comply to the
    following rules:

    \list
Tobias Hunger's avatar
Tobias Hunger committed
38
        \li The most important rule is: KISS (keep it short and simple). Always
39 40
            choose the simpler implementation option over the more complicated one.
            This makes maintenance a lot easier.
Tobias Hunger's avatar
Tobias Hunger committed
41
        \li Write good C++ code. That is, readable, well commented when necessary,
42
            and object-oriented.
Tobias Hunger's avatar
Tobias Hunger committed
43
        \li Take advantage of Qt. Do not re-invent the wheel. Think about which parts
44 45
            of your code are generic enough that they might be incorporated into
            Qt instead of Qt Creator.
Tobias Hunger's avatar
Tobias Hunger committed
46
        \li Adapt the code to the existing structures in Qt Creator.
47 48
            If you have improvement ideas, discuss them with other developers
            before writing the code.
Tobias Hunger's avatar
Tobias Hunger committed
49
        \li Follow the guidelines in \l{Code Constructs}, \l{Formatting}, and
50
            \l{Patterns and Practices}.
Tobias Hunger's avatar
Tobias Hunger committed
51
        \li Document interfaces. Right now we use qdoc, but changing to doxygen
52 53
            is being considered.
        \endlist
54 55


56
    \section1 Submitting Code
57

Eike Ziller's avatar
Eike Ziller committed
58
    To submit code to Qt Creator, you must understand the tools and mechanics as well as
59
    the philosophy behind Qt development. For more information about how to set up
Eike Ziller's avatar
Eike Ziller committed
60 61 62
    the development environment for working on Qt Creator and how to submit code
    and documentation for inclusion, see
    \l{http://wiki.qt-project.org/index.php/Main_Page}{Guidelines for Contributions to the Qt Project}.
63

64
    \section1 Binary and Source Compatibility
65

66 67 68 69 70
    The following list describes how the releases are numbered and defines
    \e {binary compatibility} and \e {source code compatibility} between
    releases:

    \list
71 72
        \li \QC 3.0.0 is a \e {major release}, \QC 3.1.0 is a \e {minor
            release}, and \QC 3.1.3 is a \e {patch release}.
Tobias Hunger's avatar
Tobias Hunger committed
73
        \li \e {Backward binary compatibility} means that code linked to an
74
            earlier version of the library still works.
Tobias Hunger's avatar
Tobias Hunger committed
75
        \li \e {Forward binary compatibility} means that code linked to a
76
            newer version of the library works with an older library.
Tobias Hunger's avatar
Tobias Hunger committed
77
        \li \e {Source code compatibility} means that code compiles without
78 79 80
            modification.
        \endlist

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

84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103
    However, we try to preserve backward binary compatibility and
    backward source code compatibility for patch releases within the same minor release:
    \list
        \li 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 \QC 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.
        \li 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, \QC 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.
        \li 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.
    \endlist
104

105
    For preserving backward compatibility:
106
    \list
107
        \li Do not add or remove any public API (for example global functions,
108 109 110
            public/protected/private member functions).
        \li Do not reimplement functions (not even inlines,
            nor protected or private functions).
Tobias Hunger's avatar
Tobias Hunger committed
111
        \li Check
Eike Ziller's avatar
Eike Ziller committed
112
            \l {http://wiki.qt-project.org/index.php/Binary_Compatibility_Workarounds}{Binary Compatibility Workarounds}
113
            for ways to preserve binary compatibility.
114
    \endlist
115

116 117
    For more information on binary compatibility, see
    \l{http://techbase.kde.org/Policies/Binary_Compatibility_Issues_With_C++}{Binary Compatibility Issues With C++}.
118

119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157
    From the viewpoint of \l{Plugin Specifications} this means that
    \list
        \li \QC plugins in patch releases will have the minor release as \c {compatVersion}. For
            example the plugins from version 3.1.2 will have \c {compatVersion="3.1.0"}.
        \li Pre-releases of the minor release, including the release candidate,
            will still have themselves as the \c {compatVersion}, meaning that plugins compiled
            against the final release will not load in the pre-releases.
        \li \QC plugin developers can decide if their plugin requires a certain patch release
            (or later) of other \QC plugins, or if they work with all patch releases of this minor
            version, by setting the corresponding \c {version} when declaring the dependency on
            the other plugin. The default for \QC plugins provided by the Qt Project is to require
            the latest patch release.
    \endlist

    For example, the \c {Find} plugin in \QC 3.1 beta (internal version number 3.0.82) will have
    \code
        <plugin name="Find" version="3.0.82" compatVersion="3.0.82">
          <dependencyList>
            <dependency name="Core" version="3.0.82"/>
            ....
    \endcode
    The \c {Find} plugin in \QC 3.1.0 final will have
    \code
        <plugin name="Find" version="3.1.0" compatVersion="3.1.0">
          <dependencyList>
            <dependency name="Core" version="3.1.0"/>
            ....
    \endcode
    The \c {Find} plugin in \QC 3.1.1 patch release will have version 3.1.1, will be
    backward binary compatible with \c {Find} plugin version 3.1.0 (\c {compatVersion="3.1.0"}),
    and will require a \c {Core} plugin that is binary backward compatible with \c {Core}
    plugin version 3.1.1:
    \code
        <plugin name="Find" version="3.1.1" compatVersion="3.1.0">
          <dependencyList>
            <dependency name="Core" version="3.1.1"/>
            ....
    \endcode

158
    \section1 Code Constructs
159

160 161 162
    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++.
163

164
    \list
Tobias Hunger's avatar
Tobias Hunger committed
165
        \li Prefer preincrement to postincrement whenever possible.
166 167 168
            Preincrement is potentially faster than postincrement. Just
            think about the obvious implementations of pre/post-increment. This
            rule applies to decrement too:
169

170 171 172
            \code
            ++T;
            --U;
173

174
            -NOT-
175

176 177 178
            T++;
            U--;
            \endcode
179

Tobias Hunger's avatar
Tobias Hunger committed
180
        \li Try to minimize evaluation of the same code over and over. This is
181
            aimed especially at loops:
182

183
            \code
184

185 186 187 188
            Container::iterator end = large.end();
            for (Container::iterator it = large.begin(); it != end; ++it) {
                    ...;
            }
189

190
            -NOT-
191

192 193 194 195 196
            for (Container::iterator it = large.begin();
                 it != large.end(); ++it) {
                    ...;
            }
            \endcode
hjk's avatar
hjk committed
197 198


Tobias Hunger's avatar
Tobias Hunger committed
199
        \li You can use the Qt \c foreach loop in non-time-critical code with a Qt
200 201
            container. It is a nice way to keep line noise down and to give the
            loop variable a proper name:
hjk's avatar
hjk committed
202

203 204 205
            \code
                foreach (QWidget *widget, container)
                    doSomething(widget);
206

207
                -NOT-
hjk's avatar
hjk committed
208

209 210 211 212
                Container::iterator end = container.end();
                for (Container::iterator it = container.begin(); it != end; ++it)
                    doSomething(*it);
            \endcode
213

214 215
            Make the loop variable const, if possible. This might prevent
            unnecessary detaching of shared data:
hjk's avatar
hjk committed
216

217 218 219
            \code
                foreach (const QString &name, someListOfNames)
                    doSomething(name);
hjk's avatar
hjk committed
220

221
                - NOT -
222

223 224 225
                foreach (QString name, someListOfNames)
                    doSomething(name);
            \endcode
226

227
        \endlist
228

229
    \section1 Formatting
230

231
    \section2 Capitalizing Identifiers
232

233
    Use \l{http://en.wikipedia.org/wiki/CamelCase}{camel case} in identifiers.
234

235
    Capitalize the first word in an identifier as follows:
236

237
    \list
Tobias Hunger's avatar
Tobias Hunger committed
238 239 240 241
        \li Class names begin with a capital letter.
        \li Function names begin with a lower case letter.
        \li Variable names begin with a lower case letter.
        \li Enum names and values begin with a capital letter. Enum values
242 243 244 245 246 247
            contain some part of the name of the enum type.
    \endlist

    \section2 Whitespace

    \list
Tobias Hunger's avatar
Tobias Hunger committed
248 249 250
        \li Use four spaces for indentation, no tabs.
        \li Use blank lines to group statements together where suited.
        \li Always use only one blank line.
251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305
    \endlist

    \section3 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:

    \code
    char *blockOfMemory = (char *)malloc(data.size());
    char *blockOfMemory = reinterpret_cast<char *>(malloc(data.size()));

    -NOT-

    char* blockOfMemory = (char* ) malloc(data.size());
    \endcode

    Of course, in this particulare case, using \c new might be an even better
    option.

    \section3  Operator Names and Parentheses

    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:

    \code
    operator==(type)

    -NOT-

    operator == (type)
    \endcode

    \section3 Function Names and Parentheses

    Do not use spaces between function names and parentheses:

    \code
    void mangle()

    -NOT-

    void mangle ()
    \endcode

    \section3 Keywords

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

    \code
    if (foo) {
    }

    -NOT-
306

307 308
    if(foo){
    }
309
    \endcode
310

hjk's avatar
hjk committed
311 312 313 314 315
    \section3 Comments

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

316 317 318 319 320 321 322
    \section2 Braces

    As a base rule, place the left curly brace on the same line as the
    start of the statement:

    \code
    if (codec) {
323 324
    }

325
    -NOT-
326 327 328 329

    if (codec)
    {
    }
330
    \endcode
331

332 333
    Exception: Function implementations and class declarations always have
    the left brace in the beginning of a line:
334

335
    \code
336 337 338 339 340 341 342 343
    static void foo(int g)
    {
        qDebug("foo: %i", g);
    }

    class Moo
    {
    };
344 345 346 347 348 349 350 351 352 353 354 355 356 357
    \endcode

    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:

    \code
    if (address.isEmpty())
        return false;

    for (int i = 0; i < 10; ++i)
        qDebug("%i", i);

    -NOT-
358 359 360 361 362 363 364 365

    if (address.isEmpty()) {
        return false;
    }

    for (int i = 0; i < 10; ++i) {
        qDebug("%i", i);
    }
366
    \endcode
367

368 369
    Exception 1: Use braces also if the parent statement covers several
    lines or if it wraps:
370

371
    \code
372 373
    if (address.isEmpty()
            || !isValid()
Leena Miettinen's avatar
Leena Miettinen committed
374
            || !codec) {
375
        return false;
Leena Miettinen's avatar
Leena Miettinen committed
376
    }
377
    \endcode
378

379
    \note This could be re-written as:
380

381
    \code
382 383 384 385 386 387 388 389
    if (address.isEmpty())
        return false;

    if (!isValid())
        return false;

    if (!codec)
        return false;
390
    \endcode
391

392 393 394 395 396
    Exception 2: Use braces also in if-then-else blocks where either the
    if-code or the else-code covers several lines:

    \code
    if (address.isEmpty()) {
397
        --it;
398
    } else {
399 400 401 402
        qDebug("%s", qPrintable(address));
        ++it;
    }

403 404 405
    -NOT-

    if (address.isEmpty())
406
        --it;
407
    else {
408 409 410
        qDebug("%s", qPrintable(address));
        ++it;
    }
411
    \endcode
412

413 414
    \code
    if (a) {
415 416 417 418
        if (b)
            ...
        else
            ...
419
    }
420

421 422 423
    -NOT-

    if (a)
424 425 426 427
        if (b)
            ...
        else
            ...
428
    \endcode
429

430
    Use curly braces when the body of a conditional statement is empty:
431

432
    \code
433 434
    while (a) {}

435
    -NOT-
436

437 438 439 440 441 442
    while (a);
    \endcode

    \section2 Parentheses

    Use parentheses to group expressions:
443

444
    \code
445 446
    if ((a && b) || c)

447 448 449 450
    -NOT-

    if (a && b || c)
    \endcode
451

452
    \code
453 454
    (a + b) & c

455
    -NOT-
456

457 458
    a + b & c
    \endcode
459

460
    \section2 Line Breaks
461

462
    \list
Tobias Hunger's avatar
Tobias Hunger committed
463 464 465 466
        \li Keep lines shorter than 100 characters.
        \li Insert line breaks if necessary.
        \li Commas go at the end of a broken line.
        \li Operators start at the beginning of the new line.
467 468 469 470 471
            \code
            if (longExpression
                || otherLongExpression
                || otherOtherLongExpression) {
            }
472

473
            -NOT-
474

475 476 477 478 479 480
            if (longExpression ||
                otherLongExpression ||
                otherOtherLongExpression) {
            }
            \endcode
    \endlist
481

482
    \section2 Declarations
483

484
    \list
Tobias Hunger's avatar
Tobias Hunger committed
485
        \li Use this order for the access sections of your class: public,
486 487 488
            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).
489

Tobias Hunger's avatar
Tobias Hunger committed
490
        \li Avoid declaring global objects in the declaration file of the class.
491
            If the same variable is used for all objects, use a static member.
492

Tobias Hunger's avatar
Tobias Hunger committed
493
        \li Use \c{class} instead of \c{struct}. Some compilers mangle that
494 495
            difference into the symbol names and spit out warnings if a struct
            declaration is followed by a class definition. To avoid ongoing
Sergio Ahumada's avatar
Sergio Ahumada committed
496
            changes from one to the other we declare \c{class} the preferred way.
497

498
    \endlist
499

500
    \section3 Declaring Variables
501

502
    \list
Tobias Hunger's avatar
Tobias Hunger committed
503
        \li Avoid global variables of class type to rule out initialization order problems.
504
            Consider using \c Q_GLOBAL_STATIC if they cannot be avoided.
Tobias Hunger's avatar
Tobias Hunger committed
505
        \li Declare global string literals as
506 507 508
            \code
            const char aString[] = "Hello";
            \endcode
Tobias Hunger's avatar
Tobias Hunger committed
509
        \li Avoid short names (such as, a, rbarr, nughdeget) whenever possible.
510 511
            Use single-character variable names only for counters and
            temporaries, where the purpose of the variable is obvious.
Tobias Hunger's avatar
Tobias Hunger committed
512
        \li Declare each variable on a separate line:
513 514 515 516 517
            \code
            QString a = "Joe";
            QString b = "Foo";

            -NOT-
518

519 520
            QString a = "Joe", b = "Foo";
            \endcode
521

522 523 524 525 526 527 528 529 530 531
            \note \c{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
            \c {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.
532

Tobias Hunger's avatar
Tobias Hunger committed
533
        \li Avoid abbreviations:
534

535 536 537 538 539
            \code
            int height;
            int width;
            char *nameOfThis;
            char *nameOfThat;
540

541 542 543 544 545
            -NOT-

            int a, b;
            char *c, *d;
            \endcode
con's avatar
con committed
546

Tobias Hunger's avatar
Tobias Hunger committed
547
        \li Wait with declaring a variable until it is needed. This is especially
548 549
            important when initialization is done at the same time.
    \endlist
con's avatar
con committed
550

hjk's avatar
hjk committed
551 552 553
    \section2 Namespaces

    \list
Tobias Hunger's avatar
Tobias Hunger committed
554 555 556 557
        \li Put the left curly brace on the same line as the \namespace keyword.
        \li Do not indent declarations or definitions inside.
        \li Optional, but recommended if the namespaces spans more than a few lines:
            Add a comment after the right curly brace repeating the namespace.
hjk's avatar
hjk committed
558 559 560 561 562 563 564 565 566

        \code
        namespace MyPlugin {

        void someFunction() { ... }

        }  // namespace MyPlugin
        \endcode

Tobias Hunger's avatar
Tobias Hunger committed
567 568
        \li As an exception, if there is only a single class declaration inside
            the namespace, all can go on a single line:
hjk's avatar
hjk committed
569 570 571 572 573
        \code
        namespace MyPlugin { class MyClass; }
        \endcode
    \endlist

574
    \section1 Patterns and Practices
con's avatar
con committed
575

576
    \target coding-rules-namespacing
Eike Ziller's avatar
Eike Ziller committed
577 578
    \section2 Namespacing

Eike Ziller's avatar
Eike Ziller committed
579
    Read \l {http://wiki.qt-project.org/index.php/Qt_In_Namespace}{Qt In Namespace}
Eike Ziller's avatar
Eike Ziller committed
580 581 582 583
    and keep in mind that all of Qt Creator is \e{namespace aware} code.

    The namespacing policy within Qt Creator is as follows:
    \list
Tobias Hunger's avatar
Tobias Hunger committed
584 585 586 587 588
        \li 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. \c{MyPlugin}.
        \li Classes/Symbols of a library or plugin that are not exported are in
            an additional \c{Internal} namespace, e.g. \c{MyPlugin::Internal}.
Eike Ziller's avatar
Eike Ziller committed
589 590
    \endlist

591
    \section2 Passing File Names
con's avatar
con committed
592

593 594 595 596
    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
597 598
    QDir::toNativeSeparators. Consider using Utils::FileName::fromUserInput(QString)
    and Utils::FileName::toUserOutput() for these tasks.
con's avatar
con committed
599

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

603
    \section2 Plugin Extension Points
con's avatar
con committed
604

605 606 607 608 609 610 611
    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 \e 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.
con's avatar
con committed
612

613 614 615 616 617 618 619
    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 \gui {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.
con's avatar
con committed
620

621
    \section2 Using the Global Object Pool
622

623 624 625 626 627 628 629 630 631 632 633 634
    You can add objects to the global object pool via
    \l{ExtensionSystem::PluginManager::addObject()}, and retrieve objects
    of a specific type again via
    \l{ExtensionSystem::PluginManager::getObjects()}.  This should mostly
    be used for implementations of \l{Plugin Extension Points}.

    \note Do not put a singleton into the pool, and do not retrieve
    it from there. Use the singleton pattern instead.

    \section2 C++ Features

    \list
Tobias Hunger's avatar
Tobias Hunger committed
635
        \li Do not use exceptions, unless you know what you do.
636

Tobias Hunger's avatar
Tobias Hunger committed
637
        \li Do not use RTTI (Run-Time Type Information; that is, the typeinfo
638 639
            struct, the dynamic_cast or the typeid operators, including throwing
            exceptions), unless you know what you do.
640

Tobias Hunger's avatar
Tobias Hunger committed
641
        \li Do not use virtual inheritance, unless you know what you do.
642

Tobias Hunger's avatar
Tobias Hunger committed
643
        \li Use templates wisely, not just because you can.
644 645 646 647

            Hint: Use the compile autotest to see whether a C++ feature is supported
            by all compilers in the test farm.

Tobias Hunger's avatar
Tobias Hunger committed
648
        \li All code is ASCII only (7-bit characters only, run \c {man ascii} if unsure)
649
            \list
Tobias Hunger's avatar
Tobias Hunger committed
650
                \li Rationale: We have too many locales inhouse and an unhealthy
651 652 653
                    mix of UTF-8 and Latin1 systems. Usually, characters > 127 can
                    be broken without you even knowing by clicking Save in your
                    favourite editor.
Tobias Hunger's avatar
Tobias Hunger committed
654 655
                \li For strings: Use \\nnn (where nnn is the octal representation
                    of whatever locale you want your string in) or \\xnn (where nn
656 657
                    is hexadecimal).
                    For example: QString s = QString::fromUtf8("\\213\\005");
Tobias Hunger's avatar
Tobias Hunger committed
658
              \li For umlauts in documentation, or other non-ASCII characters,
659 660 661
                  either use the qdoc \c {\unicode} command or use the relevant macro.
                  For example: \c{\uuml} for \uuml.
           \endlist
662

Tobias Hunger's avatar
Tobias Hunger committed
663
        \li Use static keywords instead of anonymous namespaces whenever possible.
664 665 666
            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
667 668
            (ISO/IEC 14882, 7.1.1/6, or see various discussions about this on the gcc
            mailing lists).
669
    \endlist
670

671
    \section3 Null Pointers
672

673 674
    Using a plain zero (0) for null pointer constants is always correct and
    least effort to type.
675

676 677
    \code
    void *p = 0;
678

679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697
    -NOT-

    void *p = NULL;

    -NOT-

    void *p = '\0';

    -NOT-

    void *p = 42 - 7 * 6;
    \endcode

    \note As an exception, imported third party code as well as code
    interfacing the native APIs (src/support/os_*) can use NULL.

    \section2 Using QObject

    \list
Tobias Hunger's avatar
Tobias Hunger committed
698
        \li Every QObject subclass must have a Q_OBJECT macro, even if it
699 700
            does not have signals or slots, if it is intended to be used
            with qobject_cast<>. See also \l{Casting}.
Tobias Hunger's avatar
Tobias Hunger committed
701
        \li Normalize the arguments for signals and slots
702
            (see \l{http://qt-project.org/doc/qt-4.8/qmetaobject.html#normalizedSignature}{QMetaObject::normalizedSignature}
703 704 705 706 707 708 709 710 711 712 713 714 715
            inside connect statements
            to safely make signal and slot lookup a few cycles faster.
            You can use $QTDIR/util/normalize to normalize existing code.
    \endlist

    \section2 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.

    \section2 Including Headers

    \list
Tobias Hunger's avatar
Tobias Hunger committed
716
        \li Use the following format to include Qt headers:
Tobias Hunger's avatar
Tobias Hunger committed
717 718
            \c{#include <QWhatEver>}. Do not include the module as it might have changed between
            Qt4 and Qt5.
Tobias Hunger's avatar
Tobias Hunger committed
719
        \li Arrange includes in an order that goes from specific to generic to
720
            ensure that the headers are self-contained. For example:
721
        \list
Tobias Hunger's avatar
Tobias Hunger committed
722 723 724 725 726 727
            \li \c{#include "myclass.h"}
            \li \c{#include "otherclassinplugin.h"}
            \li \c{#include <otherplugin/someclass.h>}
            \li \c{#include <QtClass>}
            \li \c{#include <stdthing>}
            \li \c{#include <system.h>}
728
        \endlist
Tobias Hunger's avatar
Tobias Hunger committed
729
        \li Enclose headers from other plugins in square brackets (<>) rather than
730 731
            quotation marks ("") to make it easier to spot external dependencies in
            the sources.
Tobias Hunger's avatar
Tobias Hunger committed
732
        \li Add empty lines between long blocks of \e peer headers and try to
733 734 735 736 737 738
            arrange the headers in alphabetic order within a block.
    \endlist

    \section2 Casting

    \list
Tobias Hunger's avatar
Tobias Hunger committed
739
        \li Avoid C casts, prefer C++ casts (\c static_cast, \c const_cast,
740 741 742
            \c reinterpret_cast) Both \c reinterpret_cast and
            C-style casts are dangerous, but at least \c reinterpret_cast
            will not remove the const modifier.
Tobias Hunger's avatar
Tobias Hunger committed
743
        \li Do not use \c dynamic_cast, use \c {qobject_cast} for QObjects, or
744
            refactor your design, for example by introducing a \c {type()}
745
            function (see QListWidgetItem), unless you know what you do.
746 747 748 749 750
    \endlist

    \section2 Compiler and Platform-specific Issues

    \list
Tobias Hunger's avatar
Tobias Hunger committed
751
        \li Be extremely careful when using the question mark operator.
752 753 754 755 756 757 758 759
            If the returned types are not identical, some compilers generate
            code that crashes at runtime (you will not even get a compiler warning):
            \code
            QString s;
            // crash at runtime - QString vs. const char *
            return condition ? s : "nothing";
            \endcode

Tobias Hunger's avatar
Tobias Hunger committed
760
        \li Be extremely careful about alignment.
761 762 763 764 765 766 767 768 769 770 771

            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 \c {const char *} is cast to a
            \c {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:
            \code
772 773 774 775 776
            union AlignHelper
            {
                char c;
                int i;
            };
777
            \endcode
778

Tobias Hunger's avatar
Tobias Hunger committed
779
        \li Anything that has a constructor or needs to run code to be
780 781 782
            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 \c {main()} or not at all).
783

784 785 786
            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:
787

788 789
            \code
            // global scope
790

791
            -NOT-
792

793 794
            // Default constructor needs to be run to initialize x:
            static const QString x;
795

796
            -NOT-
797

798 799
            // Constructor that takes a const char * has to be run:
            static const QString y = "Hello";
800

801
            -NOT-
802

803
            QString z;
804

805
            -NOT-
806

807 808 809
            // Call time of foo() undefined, might not be called at all:
            static const int i = foo();
            \endcode
810

811
            Things you can do:
812

813 814 815 816
            \code
            // global scope
            // No constructor must be run, x set at compile time:
            static const char x[] = "someText";
817

818 819
            // y will be set at compile time:
            static int y = 7;
820

821 822
            // Will be initialized statically, no code being run.
            static MyStruct s = {1, 2, 3};
823

824 825 826
            // Pointers to objects are OK, no code needed to be run to
            // initialize ptr:
            static QString *ptr = 0;
827

828
            // Use Q_GLOBAL_STATIC to create static global objects instead:
829

830
            Q_GLOBAL_STATIC(QString, s)
831

832 833 834 835 836 837 838 839 840 841
            void foo()
            {
                s()->append("moo");
            }
            \endcode

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

Tobias Hunger's avatar
Tobias Hunger committed
842
        \li A \c char is signed or unsigned dependent on the architecture. Use signed
Sergio Ahumada's avatar
Sergio Ahumada committed
843
            \c char or \c uchar if you explicitly want a signed or unsigned char.
844 845 846 847 848 849 850 851 852 853
            The following code will break on PowerPC, for example:

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

Tobias Hunger's avatar
Tobias Hunger committed
854
        \li Avoid 64-bit enum values. The AAPCS (Procedure Call Standard
855 856 857
            for the ARM Architecture) embedded ABI hard codes
            all enum values to a 32-bit integer.

Tobias Hunger's avatar
Tobias Hunger committed
858
        \li Do not mix const and non-const iterators. This will silently crash
859 860 861
            on broken compilers.
            \code
            for (Container::const_iterator it = c.constBegin(); it != c.constEnd(); ++it)
862

863
            -NOT-
864

865 866 867
            for (Container::const_iterator it = c.begin(); it != c.end(); ++it)
            \endcode
    \endlist
868

869
    \section2 Esthetics
870

871
    \list
Tobias Hunger's avatar
Tobias Hunger committed
872 873 874 875 876 877
        \li Prefer 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.
        \li Prefer verbose argument names in headers.
            Qt Creator will show the argument names in their completion box.
            It will look better in the documentation.
878
    \endlist
879

880
    \section2 Inheriting from Template or Tool Classes
881

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

885
    \list
Tobias Hunger's avatar
Tobias Hunger committed
886 887
        \li The destructors are not virtual, which can lead to memory leaks.
        \li The symbols are not exported (and mostly inline), which can lead to
888
            symbol clashes.
889 890
    \endlist

891 892 893 894
    For example, library A has class \c {Q_EXPORT X: public QList<QVariant> {};}
    and library B has class \c {Q_EXPORT Y: public QList<QVariant> {};}.
    Suddenly, QList symbols are exported from two libraries which results in a
    clash.
895

896
    \section2 Conventions for Public Header Files
897

898 899
    Our public header files have to survive the strict settings of
    some of our users. All installed headers have to follow these rules:
900

901
    \list
902

Tobias Hunger's avatar
Tobias Hunger committed
903
        \li No C style casts (\c{-Wold-style-cast}). Use \c static_cast, \c const_cast
904 905
            or \c reinterpret_cast, for basic types, use the constructor form:
            \c {int(a)} instead of \c {(int)a}. For more information, see \l{Casting}.
906

Tobias Hunger's avatar
Tobias Hunger committed
907
        \li No float comparisons (\c{-Wfloat-equal}). Use \c qFuzzyCompare to compare
908
            values with a delta. Use \c qIsNull to check whether a float is
Sergio Ahumada's avatar
Sergio Ahumada committed
909
            binary 0, instead of comparing it to 0.0, or, preferred, move
910
            such code into an implementation file.
911

912
       \li Do not hide virtual functions in subclasses (\{-Woverloaded-virtual}).
913 914 915 916 917 918 919 920 921 922 923 924 925 926
           If the baseclass A has a virtual \c {int val()} and subclass B an
           overload with the same name, \c {int val(int x)}, the A \c val function
           is hidden. Use the \c using keyword to make it visible again, and
           add the following silly workaround for broken compilers:
           \code
               class B: public A
               {
               #ifdef Q_NO_USING_KEYWORD
               inline int val() { return A::val(); }
               #else
               using A::val;
               #endif
               };
           \endcode
927

Tobias Hunger's avatar
Tobias Hunger committed
928
        \li Do not shadow variables (\c{-Wshadow}).
929

Tobias Hunger's avatar
Tobias Hunger committed
930
        \li Avoid things like \c {this->x = x;} if possible.
931

Tobias Hunger's avatar
Tobias Hunger committed
932
        \li Do not give variables the same name as functions declared in
933
            your class.
934

Tobias Hunger's avatar
Tobias Hunger committed
935
        \li To improve code readability, always check whether a preprocessor
936
            variable is defined before probing its value (\c{-Wundef}).
937

938 939
            \code
              #if defined(Foo) && Foo == 0
940

941
              -NOT-
942

943
              #if Foo == 0
944

945
              -NOT-
946

947 948
              #if Foo - 0 == 0
           \endcode
949

Tobias Hunger's avatar
Tobias Hunger committed
950 951
        \li When checking for a preprocessor define using the \c{defined}
            operator, always include the variable name in parentheses.
952 953 954 955 956 957 958 959 960

            \code
              #if defined(Foo)

              -NOT-

              #if defined Foo
           \endcode

961
    \endlist
962

hjk's avatar
hjk committed
963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087