1.. title:: clang-tidy - cppcoreguidelines-prefer-member-initializer 2 3cppcoreguidelines-prefer-member-initializer 4=========================================== 5 6Finds member initializations in the constructor body which can be converted 7into member initializers of the constructor instead. This not only improves 8the readability of the code but also positively affects its performance. 9Class-member assignments inside a control statement or following the first 10control statement are ignored. 11 12This check implements `C.49 <https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#c49-prefer-initialization-to-assignment-in-constructors>`_ from the CppCoreGuidelines. 13 14If the language version is `C++ 11` or above, the constructor is the default 15constructor of the class, the field is not a bitfield (only in case of earlier 16language version than `C++ 20`), furthermore the assigned value is a literal, 17negated literal or ``enum`` constant then the preferred place of the 18initialization is at the class member declaration. 19 20This latter rule is `C.48 <https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#c48-prefer-in-class-initializers-to-member-initializers-in-constructors-for-constant-initializers>`_ from CppCoreGuidelines. 21 22Please note, that this check does not enforce this latter rule for 23initializations already implemented as member initializers. For that purpose 24see check `modernize-use-default-member-init <modernize-use-default-member-init.html>`_. 25 26Example 1 27--------- 28 29.. code-block:: c++ 30 31 class C { 32 int n; 33 int m; 34 public: 35 C() { 36 n = 1; // Literal in default constructor 37 if (dice()) 38 return; 39 m = 1; 40 } 41 }; 42 43Here ``n`` can be initialized using a default member initializer, unlike 44``m``, as ``m``'s initialization follows a control statement (``if``): 45 46.. code-block:: c++ 47 48 class C { 49 int n{1}; 50 int m; 51 public: 52 C() { 53 if (dice()) 54 return; 55 m = 1; 56 } 57 58Example 2 59--------- 60 61.. code-block:: c++ 62 63 class C { 64 int n; 65 int m; 66 public: 67 C(int nn, int mm) { 68 n = nn; // Neither default constructor nor literal 69 if (dice()) 70 return; 71 m = mm; 72 } 73 }; 74 75Here ``n`` can be initialized in the constructor initialization list, unlike 76``m``, as ``m``'s initialization follows a control statement (``if``): 77 78.. code-block:: c++ 79 80 C(int nn, int mm) : n(nn) { 81 if (dice()) 82 return; 83 m = mm; 84 } 85 86.. option:: UseAssignment 87 88 If this option is set to `true` (default is `false`), the check will initialize 89 members with an assignment. In this case the fix of the first example looks 90 like this: 91 92.. code-block:: c++ 93 94 class C { 95 int n = 1; 96 int m; 97 public: 98 C() { 99 if (dice()) 100 return; 101 m = 1; 102 } 103 }; 104