cpp_usage_guidelines.rst 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188
  1. .. _doc_cpp_usage_guidelines:
  2. C++ usage guidelines
  3. ====================
  4. Rationale
  5. ---------
  6. Since Godot 4.0, the C++ standard used throughout the codebase is a subset of
  7. **C++17**. While modern C++ brings a lot of opportunities to write faster, more
  8. readable code, we chose to restrict our usage of C++ to a subset for a few
  9. reasons:
  10. - It makes it easier to review code in online editors. This is because engine
  11. contributors don't always have access to a full-featured IDE while reviewing
  12. code.
  13. - It makes the code easier to grasp for beginner contributors (who may not be
  14. professional C++ programmers). Godot's codebase is known to be easy to learn
  15. from, and we'd like to keep it that way.
  16. To get your pull request merged, it needs to follow the C++ usage guidelines
  17. outlined here. Of course, you can use features not allowed here in your own C++
  18. modules or GDExtensions.
  19. .. note::
  20. Prior to Godot 4.0, the C++ standard used throughout the codebase was C++03,
  21. with a handful of C++14 extensions. If you are contributing a pull request
  22. to the `3.x` branch rather than `master`, your code can't use C++17 features.
  23. Instead, your code must be able to be built with a C++14 compiler.
  24. The guidelines below don't apply to third-party dependencies, although we
  25. generally favor small libraries instead of larger solutions. See also
  26. :ref:`doc_best_practices_for_engine_contributors`.
  27. .. seealso::
  28. See :ref:`doc_code_style_guidelines` for formatting guidelines.
  29. Disallowed features
  30. -------------------
  31. **Any feature not listed below is allowed.** Using features like ``constexpr``
  32. variables and ``nullptr`` is encouraged when possible. Still, try to keep your
  33. use of modern C++ features conservative. Their use needs to serve a real
  34. purpose, such as improving code readability or performance.
  35. Standard Template Library
  36. ~~~~~~~~~~~~~~~~~~~~~~~~~
  37. We don't allow using the `STL <https://en.wikipedia.org/wiki/Standard_Template_Library>`__
  38. as Godot provides its own data types (among other things).
  39. See :ref:`doc_faq_why_not_stl` for more information.
  40. This means that pull requests should **not** use ``std::string``,
  41. ``std::vector`` and the like. Instead, use Godot's datatypes as described below.
  42. A 📜 icon denotes the type is part of :ref:`Variant <doc_variant_class>`. This
  43. means it can be used as a parameter or return value of a method exposed to the
  44. scripting API.
  45. +------------------------+--------------------------+---------------------------------------------------------------------------------------+
  46. | Godot datatype | Closest C++ STL datatype | Comment |
  47. +========================+==========================+=======================================================================================+
  48. | ``String`` 📜 | ``std::string`` | **Use this as the "default" string type.** ``String`` uses UTF-32 encoding |
  49. | | | to improve performance thanks to its fixed character size. |
  50. +------------------------+--------------------------+---------------------------------------------------------------------------------------+
  51. | ``StringName`` 📜 | ``std::string`` | Uses string interning for fast comparisons. Use this for static strings that are |
  52. | | | referenced frequently and used in multiple locations in the engine. |
  53. +------------------------+--------------------------+---------------------------------------------------------------------------------------+
  54. | ``Vector`` | ``std::vector`` | **Use this as the "default" vector type.** Uses copy-on-write (COW) semantics. |
  55. | | | This means it's generally slower but can be copied around almost for free. |
  56. +------------------------+--------------------------+---------------------------------------------------------------------------------------+
  57. | ``LocalVector`` | ``std::vector`` | Closer to ``std::vector`` in semantics. In most situations, ``Vector`` should be |
  58. | | | preferred. |
  59. +------------------------+--------------------------+---------------------------------------------------------------------------------------+
  60. | ``Array`` 📜 | ``std::vector`` | Values can be of any Variant type. No static typing is imposed. |
  61. | | | Uses shared reference counting, similar to ``std::shared_ptr``. |
  62. +------------------------+--------------------------+---------------------------------------------------------------------------------------+
  63. | ``TypedArray`` 📜 | ``std::vector`` | Subclass of ``Array`` but with static typing for its elements. |
  64. | | | Not to be confused with ``Packed*Array``, which is internally a ``Vector``. |
  65. +------------------------+--------------------------+---------------------------------------------------------------------------------------+
  66. | ``Packed*Array`` 📜 | ``std::vector`` | Alias of ``Vector``, e.g. ``PackedColorArray = Vector<Color>``. |
  67. | | | Only a limited list of packed array types are available |
  68. | | | (use ``TypedArray`` otherwise). |
  69. +------------------------+--------------------------+---------------------------------------------------------------------------------------+
  70. | ``List`` | ``std::list`` | Linked list type. Generally slower than other array/vector types. Prefer using |
  71. | | | other types in new code, unless using ``List`` avoids the need for type conversions. |
  72. +------------------------+--------------------------+---------------------------------------------------------------------------------------+
  73. | ``Span`` | ``std::span`` | Represents read-only access to a contiguous array without needing to copy any data. |
  74. | | | See `pull request description <https://github.com/godotengine/godot/pull/100293>`__ |
  75. | | | for details. |
  76. +------------------------+--------------------------+---------------------------------------------------------------------------------------+
  77. | ``HashSet`` | ``std::unordered_set`` | **Use this as the "default" set type.** |
  78. +------------------------+--------------------------+---------------------------------------------------------------------------------------+
  79. | ``RBSet`` | ``std::set`` | Uses a `red-black tree <https://en.wikipedia.org/wiki/Red-black_tree>`__ |
  80. | | | for faster access. |
  81. +------------------------+--------------------------+---------------------------------------------------------------------------------------+
  82. | ``VSet`` | ``std::flat_set`` | Uses copy-on-write (COW) semantics. |
  83. | | | This means it's generally slower but can be copied around almost for free. |
  84. | | | The performance benefits of ``VSet`` aren't established, so prefer using other types. |
  85. +------------------------+--------------------------+---------------------------------------------------------------------------------------+
  86. | ``HashMap`` | ``std::unordered_map`` | **Use this as the "default" map type.** Does not preserve insertion order. |
  87. +------------------------+--------------------------+---------------------------------------------------------------------------------------+
  88. | ``AHashMap`` | ``std::unordered_map`` | Array-based implementation of a hash map. Does not preserve insertion order. |
  89. +------------------------+--------------------------+---------------------------------------------------------------------------------------+
  90. | ``OAHashMap`` | ``std::unordered_map`` | Does not preserve insertion order. |
  91. +------------------------+--------------------------+---------------------------------------------------------------------------------------+
  92. | ``RBMap`` | ``std::map`` | Uses a `red-black tree <https://en.wikipedia.org/wiki/Red-black_tree>`__ |
  93. | | | for faster access. |
  94. +------------------------+--------------------------+---------------------------------------------------------------------------------------+
  95. | ``VMap`` | ``std::flat_map`` | Uses copy-on-write (COW) semantics. |
  96. | | | This means it's generally slower but can be copied around almost for free. |
  97. | | | The performance benefits of ``VMap`` aren't established, so prefer using other types. |
  98. +------------------------+--------------------------+---------------------------------------------------------------------------------------+
  99. | ``Dictionary`` 📜 | ``std::unordered_map`` | Keys and values can be of any Variant type. No static typing is imposed. |
  100. | | | Uses shared reference counting, similar to ``std::shared_ptr``. |
  101. +------------------------+--------------------------+---------------------------------------------------------------------------------------+
  102. | ``TypedDictionary`` 📜 | ``std::unordered_map`` | Subclass of ``Dictionary`` but with static typing for its keys and values. |
  103. +------------------------+--------------------------+---------------------------------------------------------------------------------------+
  104. | ``Pair`` | ``std::pair`` | Stores a single key-value pair. |
  105. +------------------------+--------------------------+---------------------------------------------------------------------------------------+
  106. ``auto`` keyword
  107. ~~~~~~~~~~~~~~~~
  108. Please don't use the ``auto`` keyword for type inference. While it can avoid
  109. repetition, it can also lead to confusing code:
  110. .. code-block:: cpp
  111. // Not so confusing...
  112. auto button = memnew(Button);
  113. // ...but what about this?
  114. auto result = EditorNode::get_singleton()->get_complex_result();
  115. Keep in mind hover documentation often isn't readily available for pull request
  116. reviewers. Most of the time, reviewers will use GitHub's online viewer to review
  117. pull requests.
  118. The ``auto`` keyword can be used in some special cases, like C++ lambda or Objective-C block
  119. definitions and C++ templates. Please ask before using templates with ``auto`` in a pull request.
  120. .. code-block:: cpp
  121. // Full type definitions.
  122. void (*mult64to128)(uint64_t, uint64_t, uint64_t &, uint64_t &) = [](uint64_t u, uint64_t v, uint64_t &h, uint64_t &l) { ... }
  123. void (^JOYSTICK_LEFT)(GCControllerDirectionPad *__strong, float, float) = ^(GCControllerDirectionPad *dpad, float xValue, float yValue) { ... }
  124. // Less clutter with auto.
  125. auto mult64to128 = [](uint64_t u, uint64_t v, uint64_t &h, uint64_t &l) { ... }
  126. auto JOYSTICK_LEFT = ^(GCControllerDirectionPad *dpad, float xValue, float yValue) { ... }
  127. // Compare function for different types.
  128. template <typename T1, typename T2>
  129. constexpr auto MIN(const T1 m_a, const T2 m_b) {
  130. return m_a < m_b ? m_a : m_b;
  131. }
  132. We chose to forbid ``auto`` in all other cases. Thank you for your understanding.
  133. Lambdas
  134. ~~~~~~~
  135. Lambdas should be used conservatively when they make code effectively faster or
  136. simpler, and do not impede readability. Please ask before using lambdas in a
  137. pull request.
  138. ``#ifdef``-based include guards
  139. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  140. Starting with 4.5, all files now use the ``#pragma once`` directive, as they
  141. improve readability and declutter macros. Use of ``#ifdef``-based include
  142. guards are now actively discouraged.
  143. ``try``-``catch`` blocks
  144. ~~~~~~~~~~~~~~~~~~~~~~~~
  145. C++ style exception handling using ``try`` and ``catch`` blocks is forbidden.
  146. This restriction is in place for several reasons, including performance, binary
  147. size and code complexity.
  148. Use :ref:`doc_common_engine_methods_and_macros_error_macros` instead.
  149. .. seealso::
  150. See :ref:`doc_code_style_guidelines_header_includes` for guidelines on sorting
  151. includes in C++ and Objective-C files.