Rule A12-1-3 (required, implementation, automated)
If all user-defined constructors of a class initialize data members with constant values that are the same across all constructors, then data members shall be initialized using NSDMI instead.
Rationale
Using NSDMI lets the compiler to generate the function that can be more efficient than a user-defined constructor that initializes data member variables with predefined constant values.
Example
// $Id: A12-1-3.cpp 291949 2017-10-19 21:26:22Z michal.szczepankiewicz $
#include <cstdint>
#include <string>
class A
{
public:
A() : x(0), y(0.0F), str() // Non-compliant
{
}
// ...
private:
std::int32_t x;
float y;
std::string str;
};
class B
{
public:
// ...
private:
std::int32_t x = 0;
// Compliant
float y = 0.0F;
// Compliant
std::string str = ""; // Compliant
};
class C
{
public:
C() : C(0, 0.0F, decltype(str)()) // Compliant
{
}
C(std::int32_t i, float f, std::string s) : x(i), y(f), str(s) // Compliant
{
}
// ...
private:
std::int32_t x =
0;// Non-compliant - there’s a constructor that initializes C
// class with user input
float y = 0.0F; // Non-compliant - there’s a constructor that initializes C
// class with user input
std::string str = ""; // Non-compliant - there’s a constructor that
// initializes C class with user input
};
See also
C++ Core Guidelines [11]: C.45: Don’t define a default constructor that only initializes data members; use in-class member initializers instead.