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 13<https://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines#c49-prefer-initialization-to-assignment-in-constructors>`_ 14from the C++ Core Guidelines. 15 16Please note, that this check does not enforce rule `C.48 17<https://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines#c48-prefer-in-class-initializers-to-member-initializers-in-constructors-for-constant-initializers>`_ 18from the C++ Core Guidelines. For that purpose 19see check :doc:`modernize-use-default-member-init <../modernize/use-default-member-init>`. 20 21Example 1 22--------- 23 24.. code-block:: c++ 25 26 class C { 27 int n; 28 int m; 29 public: 30 C() { 31 n = 1; // Literal in default constructor 32 if (dice()) 33 return; 34 m = 1; 35 } 36 }; 37 38Here ``n`` can be initialized in the constructor initializer list, unlike 39``m``, as ``m``'s initialization follows a control statement (``if``): 40 41.. code-block:: c++ 42 43 class C { 44 int n; 45 int m; 46 public: 47 C(): n(1) { 48 if (dice()) 49 return; 50 m = 1; 51 } 52 }; 53 54Example 2 55--------- 56 57.. code-block:: c++ 58 59 class C { 60 int n; 61 int m; 62 public: 63 C(int nn, int mm) { 64 n = nn; // Neither default constructor nor literal 65 if (dice()) 66 return; 67 m = mm; 68 } 69 }; 70 71Here ``n`` can be initialized in the constructor initializer list, unlike 72``m``, as ``m``'s initialization follows a control statement (``if``): 73 74.. code-block:: c++ 75 76 C(int nn, int mm) : n(nn) { 77 if (dice()) 78 return; 79 m = mm; 80 } 81