AutosarC++17_03-A12.1.3

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

Required inputs: IR

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 pre-defined constant values.

Example
// $Id: A12-1-3.cpp 271696 2017-03-23 09:23:09Z piotr.tanski $
#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()
: x(0), y(0.0F), 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 [10]: C.45: Don’t define a default constructor that only initializes data members; use in-class member initializers instead.

Possible Messages

Key

Text

Severity

Disabled

use_nsdmi

Use NSDMI for common constant initializations ({}).

None

False

Options

allow_constructors_of_types

allow_constructors_of_types : set[bauhaus.analysis.config.QualifiedName] = set()

List of fully qualified type names which constructors are considered literals, without regard to the actual arguments.
 

allow_literal_like_constructors

allow_literal_like_constructors : bool = False

Whether to consider constructors that take only literals as arguments a literal. If set to true, this is checked recursively.
 

min_number_common_inits

min_number_common_inits : int = 1

Minimum number (inclusive) of common initializations to enforce use of NSDMI.